@oddin-gg/havik-player 2.27.1 → 2.28.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 +3 -3
- package/dist/havik-player.global.js.map +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +31 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +424 -343
- package/dist/index.js.map +1 -1
- package/docs/API.md +48 -23
- package/embed/index.html +1 -1
- package/examples/vanilla.html +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var HavikPlayer=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){"@babel/helpers - typeof";return t=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},t(e)}function n(e,n){if(t(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,n||`default`);if(t(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(e)}function r(e){var r=n(e,`string`);return t(r)==`symbol`?r:r+``}function i(e,t,n){return(t=r(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var a=class extends Error{constructor(e,t,n,r){super(n),i(this,`code`,void 0),i(this,`httpStatus`,void 0),i(this,`retryAfterMs`,void 0),i(this,`requestId`,void 0),i(this,`serverCode`,void 0),i(this,`liveStartsAtMs`,void 0),i(this,`country`,void 0),this.name=`PlaybackError`,this.code=e,this.httpStatus=t,this.retryAfterMs=r?.retryAfterMs,this.requestId=r?.requestId,this.serverCode=r?.serverCode,this.liveStartsAtMs=r?.liveStartsAtMs,this.country=r?.country,r?.cause!==void 0&&(this.cause=r.cause)}};function o(e){switch(e){case 400:return`INVALID_URN`;case 401:return`UNAUTHORIZED`;case 403:return`FORBIDDEN`;case 404:return`NOT_FOUND`;case 410:return`GONE`;case 425:return`TOO_EARLY`;case 429:return`RATE_LIMITED`;case 451:return`GEO_DENIED`;case 503:return`UNAVAILABLE`;default:return`INTERNAL`}}function s(e){let t=e;if(typeof e==`string`){if(e===``)return;try{t=JSON.parse(e)}catch{return}}if(!t||typeof t!=`object`)return;let n=t.error;if(typeof n==`string`)return n===``?void 0:n;if(n&&typeof n==`object`){let e=n.code;if(typeof e==`string`&&e!==``)return e}}function c(e,t){return e===401?`UNAUTHORIZED`:e===403?t===`cdm_revoked`?`DRM_DEVICE_REVOKED`:`FORBIDDEN`:`DRM_CLIENT`}var l=new Set([`TOO_EARLY`,`UNAVAILABLE`,`RATE_LIMITED`,`NETWORK`]);function u(e){return l.has(e)}async function d(e){let t=typeof e==`function`?await e():e;if(!t||!t.apiKey)throw Error(`havik-player: credential is missing an apiKey`);return t}function f(e){return e===`live`||e===`ended`||e===`upcoming`||e===`pending`?e:`upcoming`}function p(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=typeof n.urn==`string`?n.urn:``,r=typeof n.name==`string`?n.name:``;if(!e&&!r)continue;let i={urn:e,name:r,isHome:n.isHome===!0};typeof n.logoUrl==`string`&&m(n.logoUrl)&&(i.logoUrl=n.logoUrl),t.push(i)}return t.length>0?t:void 0}function m(e){try{return new URL(e).protocol===`https:`}catch{return!1}}function h(e,t){let n=e.replace(/\/+$/,``),r;try{r=new URL(n+t)}catch{throw new a(`INTERNAL`,0,`invalid baseUrl: ${JSON.stringify(e)}`)}if(r.protocol!==`https:`&&r.protocol!==`http:`)throw new a(`INTERNAL`,0,`baseUrl must be http(s), got: ${JSON.stringify(e)}`);return r.toString()}function g(e){if(!e)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.round(t*1e3));let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(0,n-Date.now())}async function _(e,t){let n=await d(t.credential),r=t.headers??new Headers;if(t.apiHeaders)for(let[e,n]of Object.entries(t.apiHeaders))r.has(e)||r.set(e,n);r.set(`x-api-key`,n.apiKey);try{return await fetch(e,{method:t.method??`GET`,headers:r,body:t.body,signal:t.signal,cache:`no-store`,credentials:`omit`,mode:`cors`})}catch(e){throw t.signal?.aborted?new a(`ABORTED`,0,`request aborted`,{cause:e}):new a(`NETWORK`,0,`network request failed: ${v(e)}`,{cause:e})}}function v(e){return e instanceof Error?e.message:String(e)}var y=new Set;function b(e,t=e){y.has(t)||(y.add(t),console.warn(`havik-player: ${e}`))}var x=1e3,S=3e4,C=6e5,w=3e5,T=1e3,E={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function D(e){let t=e===!0||e===!1?{}:e,n=Math.max(T,t.floorMs??x),r=Math.max(n,t.ceilMs??S),i=Math.max(0,t.imminentMs??C),a=Math.max(r,t.sanityFloorMs??w);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:O(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function O(e){if(e==null)return;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function k(e,t,n){return Math.min(n,Math.max(t,e))}function A(e){return Math.round(e*(1+.15*Math.random()))}function j(e,t,n,r){let i=r??n.kickoffMs,a=i==null?void 0:Math.max(0,i-t),o=Math.max(n.floorMs,e??0);if(a==null||a<=n.imminentMs)return{delay:k(e??n.floorMs,o,n.ceilMs),ttkMs:a};let s=Math.min(Math.floor(a/10),n.sanityFloorMs,a);return{delay:Math.max(o,s),ttkMs:a}}function M(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new a(`ABORTED`,0,`wait-for-live aborted`));return}let i=()=>{clearTimeout(o),r(new a(`ABORTED`,0,`wait-for-live aborted`))},o=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}async function N(e,t,n){let r=D(t),i=Date.now(),o=r.timeoutMs==null?1/0:i+r.timeoutMs,s=0,c;for(;;){if(n?.aborted)throw new a(`ABORTED`,0,`wait-for-live aborted`);try{return await e()}catch(e){if(!(e instanceof a)||!u(e.code))throw e;s+=1,e.liveStartsAtMs!=null&&Number.isFinite(e.liveStartsAtMs)&&(c=e.liveStartsAtMs);let t=Date.now(),l=j(e.retryAfterMs,t,r,c),d=l.ttkMs,f=l.delay;if(r.jitter&&(f=A(f)),t+f>o)throw new a(`TIMEOUT`,e.httpStatus,`timed out after ${r.timeoutMs}ms waiting for the stream to go live`,{retryAfterMs:e.retryAfterMs,cause:e});r.onState?.({phase:E[e.code]??`unavailable`,retryInMs:f,attempt:s,elapsedMs:t-i,ttkMs:d}),await M(f,n)}}}async function ee(e){if(!e.matchUrn||typeof e.matchUrn!=`string`)throw new a(`INVALID_URN`,0,`resolveStream: a non-empty matchUrn is required`);let t=await _(h(e.baseUrl,`/v1/playback/${encodeURIComponent(e.matchUrn)}`),{credential:e.credential,signal:e.signal,apiHeaders:e.apiHeaders});if(!t.ok)throw await ne(t);return oe(await t.json(),e.matchUrn)}function te(e){let t=()=>ee(e);return e.waitForLive?N(t,e.waitForLive,e.signal):t()}async function ne(e){let t=g(e.headers.get(`retry-after`)),n=e.headers.get(`x-request-id`)??e.headers.get(`x-amzn-requestid`)??void 0,r=e.statusText||`HTTP ${e.status}`,i,s,c;try{let t=await e.json();if(t?.error?.message&&(r=t.error.message),t?.error?.code&&(i=t.error.code),typeof t?.liveStartsAt==`string`){let e=Date.parse(t.liveStartsAt);Number.isFinite(e)&&(s=e)}e.status===451&&typeof t?.country==`string`&&/^[A-Z]{2}$/.test(t.country)&&(c=t.country)}catch{}return new a(o(e.status),e.status,r,{retryAfterMs:t,requestId:n,serverCode:i,liveStartsAtMs:s,country:c})}var re=new Set([`matchUrn`,`protocol`,`drmEnabled`,`manifestUrl`,`drm`,`serverTime`,`liveStartsAt`,`expiresAt`,`analytics`]);function ie(e,t){let n;try{n=new URL(t)}catch{throw new a(`INTERNAL`,0,`playback ${e} is not a valid URL`)}if(n.protocol!==`https:`&&n.protocol!==`http:`)throw new a(`INTERNAL`,0,`playback ${e} has a disallowed scheme: ${n.protocol}`);return t}function ae(e){if(e!==void 0){if(typeof e==`string`&&!e.endsWith(`/`))try{let t=new URL(e);if(t.protocol===`https:`&&t.href===`${t.origin}/`)return t.origin}catch{}b(`server analytics.endpoint ${JSON.stringify(e)} ignored: not a bare https origin.`)}}function oe(e,t){if(!e.manifestUrl)throw new a(`INTERNAL`,0,`playback response is missing manifestUrl`);let n=e.drmEnabled??!!e.drm,r={matchUrn:e.matchUrn??t,protocol:`hls`,drmEnabled:n,manifestUrl:ie(`manifestUrl`,e.manifestUrl),serverTime:e.serverTime??``};if(e.liveStartsAt&&(r.liveStartsAt=e.liveStartsAt),typeof e.analytics?.sid==`string`&&e.analytics.sid){r.analytics={sid:e.analytics.sid};let t=ae(e.analytics.endpoint);t&&(r.analytics.endpoint=t)}if(n&&e.drm){let t={};e.drm.widevine?.licenseUrl&&(t.widevine={licenseUrl:ie(`widevine licenseUrl`,e.drm.widevine.licenseUrl)}),e.drm.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&(t.fairplay={licenseUrl:ie(`fairplay licenseUrl`,e.drm.fairplay.licenseUrl),certificateUrl:ie(`fairplay certificateUrl`,e.drm.fairplay.certificateUrl)}),(t.widevine||t.fairplay)&&(r.drm=t)}let i={};for(let[t,n]of Object.entries(e))re.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}function se(e){return e.ownerDocument??document}function ce(e){return e.fullscreenElement??e.webkitFullscreenElement??null}function le(e,t){let n=ce(se(e));return n!=null&&(n===e||t!=null&&n===t)||e.webkitDisplayingFullscreen===!0}function ue(e,t){let n=t??e,r=se(e);if(typeof n.requestFullscreen==`function`)return r.fullscreenEnabled!==!1;if(typeof n.webkitRequestFullscreen==`function`)return r.webkitFullscreenEnabled!==!1;let i=e;return i.webkitSupportsFullscreen===!0&&typeof i.webkitEnterFullscreen==`function`||e.readyState<1}async function de(e,t){let n=t??e;if(typeof n.requestFullscreen==`function`)return await n.requestFullscreen(),!0;if(typeof n.webkitRequestFullscreen==`function`)return n.webkitRequestFullscreen(),!0;let r=e;return r.webkitSupportsFullscreen&&typeof r.webkitEnterFullscreen==`function`?(r.webkitEnterFullscreen(),!0):!1}async function fe(e,t){let n=e;if(n.webkitDisplayingFullscreen){n.webkitExitFullscreen?.();return}let r=se(e),i=ce(r);i!=null&&(i===e||t!=null&&i===t)&&(typeof r.exitFullscreen==`function`?await r.exitFullscreen():r.webkitExitFullscreen?.())}async function pe(e){let t=new URLSearchParams;e.status&&t.set(`status`,Array.isArray(e.status)?e.status.join(`,`):e.status),e.sport&&t.set(`sport`,e.sport);let n=t.toString(),r=h(e.baseUrl,`/v1/catalog`+(n?`?${n}`:``)),i=new Headers;e.etag&&i.set(`If-None-Match`,e.etag);let s=await _(r,{credential:e.credential,signal:e.signal,headers:i,apiHeaders:e.apiHeaders});if(s.status===304)return{tournaments:[],etag:e.etag,notModified:!0};if(!s.ok)throw new a(o(s.status),s.status,`catalog request failed (HTTP ${s.status})`);return{tournaments:me(await s.json()),etag:s.headers.get(`etag`)??void 0,notModified:!1}}function me(e){return(e.tournaments??[]).map(e=>{let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:f(e.status),statusRaw:e.status,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r,teams:p(e.teams)}))}})}async function he(e){let t=h(e.baseUrl,`/v1/tournaments/${encodeURIComponent(e.urn)}`),n=new Headers;e.etag&&n.set(`If-None-Match`,e.etag);let r=await _(t,{credential:e.credential,signal:e.signal,headers:n,apiHeaders:e.apiHeaders});if(r.status===304)return{etag:e.etag,notModified:!0,notFound:!1};if(r.status===404)return{notModified:!1,notFound:!0};if(!r.ok)throw new a(o(r.status),r.status,`tournament request failed (HTTP ${r.status})`);return{tournament:ge(await r.json()),etag:r.headers.get(`etag`)??void 0,notModified:!1,notFound:!1}}function ge(e){let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:f(e.status),statusRaw:e.status,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r,teams:p(e.teams)}))}}function _e(e){return e.tournaments.flatMap(e=>e.matches)}var ve=new Set([`NOT_FOUND`,`GEO_DENIED`,`GONE`,`INVALID_URN`]);function ye(e){let t=Math.max(2e3,e.intervalMs??1e4),n=new AbortController,r,i,s,c=!1,l=()=>{c||(r=setTimeout(u,t))},u=async()=>{try{let t=h(e.baseUrl,`/v1/matches/${encodeURIComponent(e.matchUrn)}`),r=new Headers;i&&r.set(`If-None-Match`,i);let c=await _(t,{credential:e.credential,signal:n.signal,headers:r,apiHeaders:e.apiHeaders});if(c.status!==304){if(!c.ok)throw new a(o(c.status),c.status,`match status request failed (HTTP ${c.status})`);i=c.headers.get(`etag`)??i;let t=await c.json(),n=f(t.status),r=typeof t.status==`string`?t.status:n,l=p(t.teams),u=JSON.stringify([r,t.datePlannedStart??null,l??null]);u!==s&&(s=u,e.onChange({matchUrn:t.matchUrn??e.matchUrn,matchName:t.matchName,status:n,statusRaw:t.status,datePlannedStart:t.datePlannedStart,teams:l}))}}catch(t){if(!n.signal.aborted){let n=t instanceof a?t:new a(`NETWORK`,0,String(t));ve.has(n.code)&&(c=!0),e.onError?.(n)}}finally{l()}};return u(),{stop(){c=!0,n.abort(),r&&clearTimeout(r)}}}var be=45e3,xe=class extends Error{constructor(e){let t=e===410;super(t?`live-state subscribe failed: HTTP ${e} — match is gone, not retrying`:e===404?`live-state subscribe failed: HTTP ${e} — match not in the catalog, retrying slowly`:`live-state subscribe failed: HTTP ${e}`),i(this,`status`,void 0),i(this,`terminal`,void 0),this.name=`LiveStateHttpError`,this.status=e,this.terminal=t}},Se=3e5;function Ce(e){let t=Math.max(250,e.minBackoffMs??1e3),n=Math.max(t,e.maxBackoffMs??15e3),r=Math.max(t,e.notFoundRetryMs??Se),i=e.idleTimeoutMs??be,a=Number.isFinite(i)&&i>0?i:0,o=new AbortController,s=!1,c=e=>new Promise(t=>{if(o.signal.aborted)return t();let n=setTimeout(t,e);o.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),l=t=>{if(s)return;e.onAlive?.();let n=`message`,r=[];for(let e of t.split(`
|
|
1
|
+
var HavikPlayer=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){"@babel/helpers - typeof";return t=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},t(e)}function n(e,n){if(t(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,n||`default`);if(t(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(e)}function r(e){var r=n(e,`string`);return t(r)==`symbol`?r:r+``}function i(e,t,n){return(t=r(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var a=class extends Error{constructor(e,t,n,r){super(n),i(this,`code`,void 0),i(this,`httpStatus`,void 0),i(this,`retryAfterMs`,void 0),i(this,`requestId`,void 0),i(this,`serverCode`,void 0),i(this,`liveStartsAtMs`,void 0),i(this,`country`,void 0),i(this,`detail`,void 0),this.name=`PlaybackError`,this.code=e,this.httpStatus=t,this.retryAfterMs=r?.retryAfterMs,this.requestId=r?.requestId,this.serverCode=r?.serverCode,this.liveStartsAtMs=r?.liveStartsAtMs,this.country=r?.country,this.detail=r?.detail,r?.cause!==void 0&&(this.cause=r.cause)}};function o(e){switch(e){case 400:return`INVALID_URN`;case 401:return`UNAUTHORIZED`;case 403:return`FORBIDDEN`;case 404:return`NOT_FOUND`;case 410:return`GONE`;case 425:return`TOO_EARLY`;case 429:return`RATE_LIMITED`;case 451:return`GEO_DENIED`;case 503:return`UNAVAILABLE`;default:return`INTERNAL`}}function s(e){let t=e;if(typeof e==`string`){if(e===``)return;try{t=JSON.parse(e)}catch{return}}if(!t||typeof t!=`object`)return;let n=t.error;if(typeof n==`string`)return n===``?void 0:n;if(n&&typeof n==`object`){let e=n.code;if(typeof e==`string`&&e!==``)return e}}function c(e,t){return e===401?`UNAUTHORIZED`:e===403?t===`cdm_revoked`?`DRM_DEVICE_REVOKED`:`FORBIDDEN`:`DRM_CLIENT`}var l=new Set([`TOO_EARLY`,`UNAVAILABLE`,`RATE_LIMITED`,`NETWORK`]);function u(e){return l.has(e)}async function d(e){let t=typeof e==`function`?await e():e;if(!t||!t.apiKey)throw Error(`havik-player: credential is missing an apiKey`);return t}function f(e){return e===`live`||e===`ended`||e===`upcoming`||e===`pending`?e:`upcoming`}function p(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=typeof n.urn==`string`?n.urn:``,r=typeof n.name==`string`?n.name:``;if(!e&&!r)continue;let i={urn:e,name:r,isHome:n.isHome===!0};typeof n.logoUrl==`string`&&m(n.logoUrl)&&(i.logoUrl=n.logoUrl),t.push(i)}return t.length>0?t:void 0}function m(e){try{return new URL(e).protocol===`https:`}catch{return!1}}function h(e,t){let n=e.replace(/\/+$/,``),r;try{r=new URL(n+t)}catch{throw new a(`INTERNAL`,0,`invalid baseUrl: ${JSON.stringify(e)}`)}if(r.protocol!==`https:`&&r.protocol!==`http:`)throw new a(`INTERNAL`,0,`baseUrl must be http(s), got: ${JSON.stringify(e)}`);return r.toString()}function g(e){if(!e)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.round(t*1e3));let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(0,n-Date.now())}async function _(e,t){let n=await d(t.credential),r=t.headers??new Headers;if(t.apiHeaders)for(let[e,n]of Object.entries(t.apiHeaders))r.has(e)||r.set(e,n);r.set(`x-api-key`,n.apiKey);try{return await fetch(e,{method:t.method??`GET`,headers:r,body:t.body,signal:t.signal,cache:`no-store`,credentials:`omit`,mode:`cors`})}catch(e){throw t.signal?.aborted?new a(`ABORTED`,0,`request aborted`,{cause:e}):new a(`NETWORK`,0,`network request failed: ${v(e)}`,{cause:e})}}function v(e){return e instanceof Error?e.message:String(e)}var y=new Set;function b(e,t=e){y.has(t)||(y.add(t),console.warn(`havik-player: ${e}`))}var x=1e3,S=3e4,C=6e5,w=3e5,T=1e3,E={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function D(e){let t=e===!0||e===!1?{}:e,n=Math.max(T,t.floorMs??x),r=Math.max(n,t.ceilMs??S),i=Math.max(0,t.imminentMs??C),a=Math.max(r,t.sanityFloorMs??w);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:O(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function O(e){if(e==null)return;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function k(e,t,n){return Math.min(n,Math.max(t,e))}function A(e){return Math.round(e*(1+.15*Math.random()))}function j(e,t,n,r){let i=r??n.kickoffMs,a=i==null?void 0:Math.max(0,i-t),o=Math.max(n.floorMs,e??0);if(a==null||a<=n.imminentMs)return{delay:k(e??n.floorMs,o,n.ceilMs),ttkMs:a};let s=Math.min(Math.floor(a/10),n.sanityFloorMs,a);return{delay:Math.max(o,s),ttkMs:a}}function M(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new a(`ABORTED`,0,`wait-for-live aborted`));return}let i=()=>{clearTimeout(o),r(new a(`ABORTED`,0,`wait-for-live aborted`))},o=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}async function N(e,t,n){let r=D(t),i=Date.now(),o=r.timeoutMs==null?1/0:i+r.timeoutMs,s=0,c;for(;;){if(n?.aborted)throw new a(`ABORTED`,0,`wait-for-live aborted`);try{return await e()}catch(e){if(!(e instanceof a)||!u(e.code))throw e;s+=1,e.liveStartsAtMs!=null&&Number.isFinite(e.liveStartsAtMs)&&(c=e.liveStartsAtMs);let t=Date.now(),l=j(e.retryAfterMs,t,r,c),d=l.ttkMs,f=l.delay;if(r.jitter&&(f=A(f)),t+f>o)throw new a(`TIMEOUT`,e.httpStatus,`timed out after ${r.timeoutMs}ms waiting for the stream to go live`,{retryAfterMs:e.retryAfterMs,cause:e});r.onState?.({phase:E[e.code]??`unavailable`,retryInMs:f,attempt:s,elapsedMs:t-i,ttkMs:d}),await M(f,n)}}}async function ee(e){if(!e.matchUrn||typeof e.matchUrn!=`string`)throw new a(`INVALID_URN`,0,`resolveStream: a non-empty matchUrn is required`);let t=await _(h(e.baseUrl,`/v1/playback/${encodeURIComponent(e.matchUrn)}`),{credential:e.credential,signal:e.signal,apiHeaders:e.apiHeaders});if(!t.ok)throw await ne(t);return oe(await t.json(),e.matchUrn)}function te(e){let t=()=>ee(e);return e.waitForLive?N(t,e.waitForLive,e.signal):t()}async function ne(e){let t=g(e.headers.get(`retry-after`)),n=e.headers.get(`x-request-id`)??e.headers.get(`x-amzn-requestid`)??void 0,r=e.statusText||`HTTP ${e.status}`,i,s,c;try{let t=await e.json();if(t?.error?.message&&(r=t.error.message),t?.error?.code&&(i=t.error.code),typeof t?.liveStartsAt==`string`){let e=Date.parse(t.liveStartsAt);Number.isFinite(e)&&(s=e)}e.status===451&&typeof t?.country==`string`&&/^[A-Z]{2}$/.test(t.country)&&(c=t.country)}catch{}return new a(o(e.status),e.status,r,{retryAfterMs:t,requestId:n,serverCode:i,liveStartsAtMs:s,country:c})}var re=new Set([`matchUrn`,`protocol`,`drmEnabled`,`manifestUrl`,`drm`,`serverTime`,`liveStartsAt`,`expiresAt`,`analytics`]);function ie(e,t){let n;try{n=new URL(t)}catch{throw new a(`INTERNAL`,0,`playback ${e} is not a valid URL`)}if(n.protocol!==`https:`&&n.protocol!==`http:`)throw new a(`INTERNAL`,0,`playback ${e} has a disallowed scheme: ${n.protocol}`);return t}function ae(e){if(e!==void 0){if(typeof e==`string`&&!e.endsWith(`/`))try{let t=new URL(e);if(t.protocol===`https:`&&t.href===`${t.origin}/`)return t.origin}catch{}b(`server analytics.endpoint ${JSON.stringify(e)} ignored: not a bare https origin.`)}}function oe(e,t){if(!e.manifestUrl)throw new a(`INTERNAL`,0,`playback response is missing manifestUrl`);let n=e.drmEnabled??!!e.drm,r={matchUrn:e.matchUrn??t,protocol:`hls`,drmEnabled:n,manifestUrl:ie(`manifestUrl`,e.manifestUrl),serverTime:e.serverTime??``};if(e.liveStartsAt&&(r.liveStartsAt=e.liveStartsAt),typeof e.analytics?.sid==`string`&&e.analytics.sid){r.analytics={sid:e.analytics.sid};let t=ae(e.analytics.endpoint);t&&(r.analytics.endpoint=t)}if(n&&e.drm){let t={};e.drm.widevine?.licenseUrl&&(t.widevine={licenseUrl:ie(`widevine licenseUrl`,e.drm.widevine.licenseUrl)}),e.drm.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&(t.fairplay={licenseUrl:ie(`fairplay licenseUrl`,e.drm.fairplay.licenseUrl),certificateUrl:ie(`fairplay certificateUrl`,e.drm.fairplay.certificateUrl)}),(t.widevine||t.fairplay)&&(r.drm=t)}let i={};for(let[t,n]of Object.entries(e))re.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}function se(e){return e.ownerDocument??document}function ce(e){return e.fullscreenElement??e.webkitFullscreenElement??null}function le(e,t){let n=ce(se(e));return n!=null&&(n===e||t!=null&&n===t)||e.webkitDisplayingFullscreen===!0}function ue(e,t){let n=t??e,r=se(e);if(typeof n.requestFullscreen==`function`)return r.fullscreenEnabled!==!1;if(typeof n.webkitRequestFullscreen==`function`)return r.webkitFullscreenEnabled!==!1;let i=e;return i.webkitSupportsFullscreen===!0&&typeof i.webkitEnterFullscreen==`function`||e.readyState<1}async function de(e,t){let n=t??e;if(typeof n.requestFullscreen==`function`)return await n.requestFullscreen(),!0;if(typeof n.webkitRequestFullscreen==`function`)return n.webkitRequestFullscreen(),!0;let r=e;return r.webkitSupportsFullscreen&&typeof r.webkitEnterFullscreen==`function`?(r.webkitEnterFullscreen(),!0):!1}async function fe(e,t){let n=e;if(n.webkitDisplayingFullscreen){n.webkitExitFullscreen?.();return}let r=se(e),i=ce(r);i!=null&&(i===e||t!=null&&i===t)&&(typeof r.exitFullscreen==`function`?await r.exitFullscreen():r.webkitExitFullscreen?.())}async function pe(e){let t=new URLSearchParams;e.status&&t.set(`status`,Array.isArray(e.status)?e.status.join(`,`):e.status),e.sport&&t.set(`sport`,e.sport);let n=t.toString(),r=h(e.baseUrl,`/v1/catalog`+(n?`?${n}`:``)),i=new Headers;e.etag&&i.set(`If-None-Match`,e.etag);let s=await _(r,{credential:e.credential,signal:e.signal,headers:i,apiHeaders:e.apiHeaders});if(s.status===304)return{tournaments:[],etag:e.etag,notModified:!0};if(!s.ok)throw new a(o(s.status),s.status,`catalog request failed (HTTP ${s.status})`);return{tournaments:me(await s.json()),etag:s.headers.get(`etag`)??void 0,notModified:!1}}function me(e){return(e.tournaments??[]).map(e=>{let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:f(e.status),statusRaw:e.status,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r,teams:p(e.teams)}))}})}async function he(e){let t=h(e.baseUrl,`/v1/tournaments/${encodeURIComponent(e.urn)}`),n=new Headers;e.etag&&n.set(`If-None-Match`,e.etag);let r=await _(t,{credential:e.credential,signal:e.signal,headers:n,apiHeaders:e.apiHeaders});if(r.status===304)return{etag:e.etag,notModified:!0,notFound:!1};if(r.status===404)return{notModified:!1,notFound:!0};if(!r.ok)throw new a(o(r.status),r.status,`tournament request failed (HTTP ${r.status})`);return{tournament:ge(await r.json()),etag:r.headers.get(`etag`)??void 0,notModified:!1,notFound:!1}}function ge(e){let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:f(e.status),statusRaw:e.status,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r,teams:p(e.teams)}))}}function _e(e){return e.tournaments.flatMap(e=>e.matches)}var ve=new Set([`NOT_FOUND`,`GEO_DENIED`,`GONE`,`INVALID_URN`]);function ye(e){let t=Math.max(2e3,e.intervalMs??1e4),n=new AbortController,r,i,s,c=!1,l=()=>{c||(r=setTimeout(u,t))},u=async()=>{try{let t=h(e.baseUrl,`/v1/matches/${encodeURIComponent(e.matchUrn)}`),r=new Headers;i&&r.set(`If-None-Match`,i);let c=await _(t,{credential:e.credential,signal:n.signal,headers:r,apiHeaders:e.apiHeaders});if(c.status!==304){if(!c.ok)throw new a(o(c.status),c.status,`match status request failed (HTTP ${c.status})`);i=c.headers.get(`etag`)??i;let t=await c.json(),n=f(t.status),r=typeof t.status==`string`?t.status:n,l=p(t.teams),u=JSON.stringify([r,t.datePlannedStart??null,l??null]);u!==s&&(s=u,e.onChange({matchUrn:t.matchUrn??e.matchUrn,matchName:t.matchName,status:n,statusRaw:t.status,datePlannedStart:t.datePlannedStart,teams:l}))}}catch(t){if(!n.signal.aborted){let n=t instanceof a?t:new a(`NETWORK`,0,String(t));ve.has(n.code)&&(c=!0),e.onError?.(n)}}finally{l()}};return u(),{stop(){c=!0,n.abort(),r&&clearTimeout(r)}}}var be=45e3,xe=class extends Error{constructor(e){let t=e===410;super(t?`live-state subscribe failed: HTTP ${e} — match is gone, not retrying`:e===404?`live-state subscribe failed: HTTP ${e} — match not in the catalog, retrying slowly`:`live-state subscribe failed: HTTP ${e}`),i(this,`status`,void 0),i(this,`terminal`,void 0),this.name=`LiveStateHttpError`,this.status=e,this.terminal=t}},Se=3e5;function Ce(e){let t=Math.max(250,e.minBackoffMs??1e3),n=Math.max(t,e.maxBackoffMs??15e3),r=Math.max(t,e.notFoundRetryMs??Se),i=e.idleTimeoutMs??be,a=Number.isFinite(i)&&i>0?i:0,o=new AbortController,s=!1,c=e=>new Promise(t=>{if(o.signal.aborted)return t();let n=setTimeout(t,e);o.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),l=t=>{if(s)return;e.onAlive?.();let n=`message`,r=[];for(let e of t.split(`
|
|
2
2
|
`)){let t=e.endsWith(`\r`)?e.slice(0,-1):e;if(t===``||t.startsWith(`:`))continue;let i=t.indexOf(`:`),a=i<0?t:t.slice(0,i),o=i<0?``:t.slice(i+1);o.startsWith(` `)&&(o=o.slice(1)),a===`event`?n=o:a===`data`&&r.push(o)}if(n===`state`&&r.length!==0)try{let t=JSON.parse(r.join(`
|
|
3
3
|
`));t&&typeof t.state==`string`&&e.onState(t)}catch{}},u=/\r\n\r\n|\n\n|\r\r/,f=async(e,t,n)=>{let r=e.getReader(),i=new TextDecoder,o=``,c=!1,d,f=()=>{a&&(clearTimeout(d),d=setTimeout(()=>{n(),r.cancel().catch(()=>{})},a))};try{for(f();;){let{value:e,done:n}=await r.read();if(n)return;e&&e.length>0&&(f(),c||(c=!0,t())),o+=i.decode(e,{stream:!0});let a;for(;(a=u.exec(o))!==null;)l(o.slice(0,a.index)),o=o.slice(a.index+a[0].length);if(s)return}}finally{clearTimeout(d),await r.cancel().catch(()=>{})}};return(async()=>{let i=t;for(;!s;){let l=new AbortController,u=()=>l.abort();o.signal.addEventListener(`abort`,u,{once:!0});let p=null,m=!1,g=!1,_,v=()=>{p=`no data for ${a}ms`,l.abort()};try{let n=await d(e.credential);if(s)return;let r=h(e.eventsBaseUrl,`/v1/events/${encodeURIComponent(e.matchUrn)}`);a&&(_=setTimeout(()=>{p=`no response headers within ${a}ms`,l.abort()},a));let o=await fetch(r,{method:`GET`,headers:{"x-api-key":n.apiKey,accept:`text/event-stream`},signal:l.signal,cache:`no-store`,credentials:`omit`,mode:`cors`});if(clearTimeout(_),s)return;if(!o.ok||!o.body){let t=new xe(o.status);m=t.terminal,g=o.status===404,e.onError?.(t)}else await f(o.body,()=>{i=t},v)}catch(t){if(s||o.signal.aborted)return;p||e.onError?.(t)}finally{clearTimeout(_),o.signal.removeEventListener(`abort`,u),l.abort()}if(s||m)return;p&&e.onError?.(Error(`live-state subscribe idle: ${p} — reconnecting`)),await c(g?Math.max(i,r):i),i=Math.min(n,i*2)}})(),{close(){s||(s=!0,o.abort())}}}function we(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var Te=`havik.player.deviceId`,Ee;function De(){if(Ee)return Ee;try{let e=globalThis.localStorage?.getItem(Te);if(e)return Ee=e,e}catch{}let e=ke();Ee=e;try{globalThis.localStorage?.setItem(Te,e)}catch{}return e}function Oe(){Ee=void 0;try{globalThis.localStorage?.removeItem(Te)}catch{}}function ke(){let e=globalThis.crypto;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(e&&typeof e.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<16;e+=1)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`));return n.slice(0,4).join(``)+`-`+n.slice(4,6).join(``)+`-`+n.slice(6,8).join(``)+`-`+n.slice(8,10).join(``)+`-`+n.slice(10,16).join(``)}function Ae(e,t,n={}){let r={"x-api-key":t.apiKey,"X-Match-Urn":e.matchUrn,"X-Device-Id":n.deviceId??De(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var je=`havik.player.bandwidth`,Me=.8,Ne=2e7,Pe=3e5;function Fe(){return globalThis.navigator?.connection}function Ie(){let e=Fe()?.type;return typeof e==`string`&&e!==``&&e!==`unknown`?e:`any`}function Le(){let e=Fe()?.downlink;return typeof e==`number`&&Number.isFinite(e)&&e>0?e*1e6:void 0}function Re(){try{let e=globalThis.localStorage?.getItem(je);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function ze(e=Date.now()){let t=Re()[Ie()];if(!t||typeof t.bps!=`number`||typeof t.at!=`number`||!Number.isFinite(t.bps)||t.bps<=0)return;let n=e-t.at;if(n<0||n>2592e5)return;let r=Le(),i=r===void 0?t.bps:Math.min(t.bps,r);return Math.round(Math.min(Ne,Math.max(Pe,i*Me)))}function Be(e,t=Date.now()){if(!Number.isFinite(e)||e<=0)return;let n=Re();n[Ie()]={bps:Math.round(e),at:t};try{globalThis.localStorage?.setItem(je,JSON.stringify(n))}catch{}}function Ve(){try{globalThis.localStorage?.removeItem(je)}catch{}}var He=new WeakMap;function Ue(e,t){let n=He.get(e);n||(n=new Map,He.set(e,n));let r=n.get(t.keySystem);if(r)return r;let i=t.createMediaKeys().catch(e=>{throw n.get(t.keySystem)===i&&n.delete(t.keySystem),e});return n.set(t.keySystem,i),i}function We(){return typeof navigator<`u`&&typeof navigator.requestMediaKeySystemAccess==`function`}var Ge=[`SW_SECURE_DECODE`,`SW_SECURE_CRYPTO`];function Ke(e){return e.startsWith(`com.widevine`)}function qe(e,t){if(!Ke(e))return t;let n=(e,t)=>{let n=e.videoCapabilities;return!n?.length||!n.some(e=>e.robustness)?!1:n.every(e=>{let n=Ge.indexOf(e.robustness);return n===-1||Ge.indexOf(t)>n})},r=Ge.flatMap(e=>t.filter(t=>n(t,e)).map(t=>({...t,videoCapabilities:t.videoCapabilities?.map(t=>({...t,robustness:e}))})));return[...t,...r]}function Je(e){return(t,n)=>We()?navigator.requestMediaKeySystemAccess(t,qe(t,n)).then(t=>({keySystem:t.keySystem,getConfiguration:()=>t.getConfiguration(),createMediaKeys:()=>Ue(e,t)})):Promise.reject(Error(`navigator.requestMediaKeySystemAccess is unavailable — EME needs a secure context (https, or localhost)`))}var Ye={video:`SW_SECURE_DECODE`,audio:`SW_SECURE_CRYPTO`,scheme:`cbcs`};function Xe(e){if(!We())return;let t=(e,t)=>({contentType:e,robustness:t,encryptionScheme:Ye.scheme});Je(e)(`com.widevine.alpha`,[{initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],audioCapabilities:[t(`audio/mp4; codecs="mp4a.40.2"`,Ye.audio)],videoCapabilities:[t(`video/mp4; codecs="avc1.42e01e"`,Ye.video)]}]).then(e=>e.createMediaKeys()).catch(()=>{})}function Ze(e){let t=Qe(e);if(/^avc[13]/.test(t))return`avc`;if(/^(hvc1|hev1)/.test(t))return`hevc`;if(/^(dvh1|dvhe)/.test(t))return`dv`;if(t.startsWith(`av01`))return`av1`;if(/^vp0?9/.test(t))return`vp9`}function Qe(e){return(e??``).trim().toLowerCase()}var $e={hevc:`hvc1.1.6.L93.90`,dv:`dvh1.05.06`,av1:`av01.0.05M.08`,vp9:`vp09.00.10.08`},et=new Map,tt=new Map;function nt(e){let t=Qe(e),n=et.get(t);if(n)return n;let r={initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],videoCapabilities:[{contentType:`video/mp4; codecs="${e.trim()}"`,robustness:Ye.video,encryptionScheme:Ye.scheme}]},i=(async()=>{try{return await navigator.requestMediaKeySystemAccess(`com.widevine.alpha`,qe(`com.widevine.alpha`,[r])),!0}catch{return!1}})().then(e=>(tt.set(t,e),e));return et.set(t,i),i}function rt(){if(We())for(let e of Object.values($e))nt(e)}function it(e){let t=Ze(e);if(t)return t===`avc`?!0:tt.get(Qe(e))??tt.get(Qe($e[t]))}var at=5e3,ot=`video/mp4; codecs="avc1.42E01E"`,st=`audio/mp4; codecs="mp4a.40.2"`,ct={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function lt(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:ot,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:st,robustness:``,encryptionScheme:`cbcs`}]}]:qe(`com.widevine.alpha`,[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:ot,robustness:Ye.video,encryptionScheme:Ye.scheme}],audioCapabilities:[{contentType:st,robustness:Ye.audio,encryptionScheme:Ye.scheme}]}])}function ut(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`probe-timeout`)),t);e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}async function dt(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??at,r={};if(typeof window<`u`&&window.isSecureContext===!1)return{verdict:`insecure-context`,detail:r};let i=typeof navigator<`u`?navigator.requestMediaKeySystemAccess?.bind(navigator):void 0;if(!i)return{verdict:`no-cdm`,detail:r};let a=!1,o=!1,s=Date.now()+n,c=()=>Math.max(1,s-Date.now());for(let e of t){let t=ct[e];if(!t){r[e]=`unknown system`;continue}for(let n of t){if(Date.now()>=s){a=!0,r[e]??=`${n}: probe-timeout`;break}try{return await ut((await ut(i(n,lt(e)),c())).createMediaKeys(),c()),r[e]=`ok (${n})`,{verdict:`supported`,system:e,detail:r}}catch(t){let i=t;r[e]=`${n}: ${(i?.name&&i.name!==`Error`?i.name:i?.message)||String(t)}`,i?.message===`probe-timeout`&&(a=!0),i?.name===`SecurityError`&&(o=!0)}}}return o?{verdict:`blocked-by-policy`,detail:r}:a?{verdict:`probe-timeout`,detail:r}:{verdict:`no-cdm`,detail:r}}var ft=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function pt(e){return ft.test(e)}var mt={integration:`https://feed-dev.oddin-video.gg`,production:`https://feed.oddin-video.gg`};function ht(e){let t=Object.prototype.hasOwnProperty.call(mt,e)?mt[e]:void 0;if(!t)throw new a(`INTERNAL`,0,`unknown env ${JSON.stringify(e)} — expected 'integration' or 'production'`);return t}var P=Number.isFinite||function(e){return typeof e==`number`&&isFinite(e)},gt=Number.isSafeInteger||function(e){return typeof e==`number`&&Math.abs(e)<=_t},_t=2**53-1||9007199254740991,F=function(e){return e.NETWORK_ERROR=`networkError`,e.MEDIA_ERROR=`mediaError`,e.KEY_SYSTEM_ERROR=`keySystemError`,e.MUX_ERROR=`muxError`,e.OTHER_ERROR=`otherError`,e}({}),I=function(e){return e.KEY_SYSTEM_NO_KEYS=`keySystemNoKeys`,e.KEY_SYSTEM_NO_ACCESS=`keySystemNoAccess`,e.KEY_SYSTEM_NO_SESSION=`keySystemNoSession`,e.KEY_SYSTEM_NO_CONFIGURED_LICENSE=`keySystemNoConfiguredLicense`,e.KEY_SYSTEM_LICENSE_REQUEST_FAILED=`keySystemLicenseRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED=`keySystemServerCertificateRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED=`keySystemServerCertificateUpdateFailed`,e.KEY_SYSTEM_SESSION_UPDATE_FAILED=`keySystemSessionUpdateFailed`,e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED=`keySystemStatusOutputRestricted`,e.KEY_SYSTEM_STATUS_INTERNAL_ERROR=`keySystemStatusInternalError`,e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR=`keySystemDestroyMediaKeysError`,e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR=`keySystemDestroyCloseSessionError`,e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR=`keySystemDestroyRemoveSessionError`,e.MANIFEST_LOAD_ERROR=`manifestLoadError`,e.MANIFEST_LOAD_TIMEOUT=`manifestLoadTimeOut`,e.MANIFEST_PARSING_ERROR=`manifestParsingError`,e.MANIFEST_INCOMPATIBLE_CODECS_ERROR=`manifestIncompatibleCodecsError`,e.LEVEL_EMPTY_ERROR=`levelEmptyError`,e.PLAYLIST_UNCHANGED_ERROR=`playlistUnchangedError`,e.LEVEL_LOAD_ERROR=`levelLoadError`,e.LEVEL_LOAD_TIMEOUT=`levelLoadTimeOut`,e.LEVEL_PARSING_ERROR=`levelParsingError`,e.LEVEL_SWITCH_ERROR=`levelSwitchError`,e.AUDIO_TRACK_LOAD_ERROR=`audioTrackLoadError`,e.AUDIO_TRACK_LOAD_TIMEOUT=`audioTrackLoadTimeOut`,e.SUBTITLE_LOAD_ERROR=`subtitleTrackLoadError`,e.SUBTITLE_TRACK_LOAD_TIMEOUT=`subtitleTrackLoadTimeOut`,e.FRAG_LOAD_ERROR=`fragLoadError`,e.FRAG_LOAD_TIMEOUT=`fragLoadTimeOut`,e.FRAG_DECRYPT_ERROR=`fragDecryptError`,e.FRAG_PARSING_ERROR=`fragParsingError`,e.FRAG_GAP=`fragGap`,e.REMUX_ALLOC_ERROR=`remuxAllocError`,e.KEY_LOAD_ERROR=`keyLoadError`,e.KEY_LOAD_TIMEOUT=`keyLoadTimeOut`,e.BUFFER_ADD_CODEC_ERROR=`bufferAddCodecError`,e.BUFFER_INCOMPATIBLE_CODECS_ERROR=`bufferIncompatibleCodecsError`,e.BUFFER_APPEND_ERROR=`bufferAppendError`,e.BUFFER_APPENDING_ERROR=`bufferAppendingError`,e.BUFFER_APPEND_NO_PROGRESS=`bufferAppendNoProgress`,e.BUFFER_STALLED_ERROR=`bufferStalledError`,e.BUFFER_FULL_ERROR=`bufferFullError`,e.BUFFER_SEEK_OVER_HOLE=`bufferSeekOverHole`,e.BUFFER_NUDGE_ON_STALL=`bufferNudgeOnStall`,e.ASSET_LIST_LOAD_ERROR=`assetListLoadError`,e.ASSET_LIST_LOAD_TIMEOUT=`assetListLoadTimeout`,e.ASSET_LIST_PARSING_ERROR=`assetListParsingError`,e.INTERSTITIAL_ASSET_ITEM_ERROR=`interstitialAssetItemError`,e.INTERNAL_EXCEPTION=`internalException`,e.INTERNAL_ABORTED=`aborted`,e.ATTACH_MEDIA_ERROR=`attachMediaError`,e.MEDIA_SOURCE_REQUIRES_RESET=`mediaSourceRequiresReset`,e.UNKNOWN=`unknown`,e}({}),L=function(e){return e.MEDIA_ATTACHING=`hlsMediaAttaching`,e.MEDIA_ATTACHED=`hlsMediaAttached`,e.MEDIA_DETACHING=`hlsMediaDetaching`,e.MEDIA_DETACHED=`hlsMediaDetached`,e.MEDIA_ENDED=`hlsMediaEnded`,e.STALL_RESOLVED=`hlsStallResolved`,e.BUFFER_RESET=`hlsBufferReset`,e.BUFFER_CODECS=`hlsBufferCodecs`,e.BUFFER_CREATED=`hlsBufferCreated`,e.BUFFER_APPENDING=`hlsBufferAppending`,e.BUFFER_APPENDED=`hlsBufferAppended`,e.BUFFER_EOS=`hlsBufferEos`,e.BUFFERED_TO_END=`hlsBufferedToEnd`,e.BUFFER_FLUSHING=`hlsBufferFlushing`,e.BUFFER_FLUSHED=`hlsBufferFlushed`,e.MANIFEST_LOADING=`hlsManifestLoading`,e.MANIFEST_LOADED=`hlsManifestLoaded`,e.MANIFEST_PARSED=`hlsManifestParsed`,e.LEVEL_SWITCHING=`hlsLevelSwitching`,e.LEVEL_SWITCHED=`hlsLevelSwitched`,e.LEVEL_LOADING=`hlsLevelLoading`,e.LEVEL_LOADED=`hlsLevelLoaded`,e.LEVEL_UPDATED=`hlsLevelUpdated`,e.LEVEL_PTS_UPDATED=`hlsLevelPtsUpdated`,e.LEVELS_UPDATED=`hlsLevelsUpdated`,e.AUDIO_TRACKS_UPDATED=`hlsAudioTracksUpdated`,e.AUDIO_TRACK_SWITCHING=`hlsAudioTrackSwitching`,e.AUDIO_TRACK_SWITCHED=`hlsAudioTrackSwitched`,e.AUDIO_TRACK_LOADING=`hlsAudioTrackLoading`,e.AUDIO_TRACK_LOADED=`hlsAudioTrackLoaded`,e.AUDIO_TRACK_UPDATED=`hlsAudioTrackUpdated`,e.SUBTITLE_TRACKS_UPDATED=`hlsSubtitleTracksUpdated`,e.SUBTITLE_TRACKS_CLEARED=`hlsSubtitleTracksCleared`,e.SUBTITLE_TRACK_SWITCH=`hlsSubtitleTrackSwitch`,e.SUBTITLE_TRACK_LOADING=`hlsSubtitleTrackLoading`,e.SUBTITLE_TRACK_LOADED=`hlsSubtitleTrackLoaded`,e.SUBTITLE_TRACK_UPDATED=`hlsSubtitleTrackUpdated`,e.SUBTITLE_FRAG_PROCESSED=`hlsSubtitleFragProcessed`,e.CUES_PARSED=`hlsCuesParsed`,e.NON_NATIVE_TEXT_TRACKS_FOUND=`hlsNonNativeTextTracksFound`,e.INIT_PTS_FOUND=`hlsInitPtsFound`,e.FRAG_LOADING=`hlsFragLoading`,e.FRAG_LOAD_EMERGENCY_ABORTED=`hlsFragLoadEmergencyAborted`,e.FRAG_LOADED=`hlsFragLoaded`,e.FRAG_DECRYPTED=`hlsFragDecrypted`,e.FRAG_PARSING_INIT_SEGMENT=`hlsFragParsingInitSegment`,e.FRAG_PARSING_USERDATA=`hlsFragParsingUserdata`,e.FRAG_PARSING_METADATA=`hlsFragParsingMetadata`,e.FRAG_PARSED=`hlsFragParsed`,e.FRAG_BUFFERED=`hlsFragBuffered`,e.FRAG_CHANGED=`hlsFragChanged`,e.FPS_DROP=`hlsFpsDrop`,e.FPS_DROP_LEVEL_CAPPING=`hlsFpsDropLevelCapping`,e.MAX_AUTO_LEVEL_UPDATED=`hlsMaxAutoLevelUpdated`,e.ERROR=`hlsError`,e.DESTROYING=`hlsDestroying`,e.KEY_LOADING=`hlsKeyLoading`,e.KEY_LOADED=`hlsKeyLoaded`,e.LIVE_BACK_BUFFER_REACHED=`hlsLiveBackBufferReached`,e.BACK_BUFFER_REACHED=`hlsBackBufferReached`,e.STEERING_MANIFEST_LOADED=`hlsSteeringManifestLoaded`,e.ASSET_LIST_LOADING=`hlsAssetListLoading`,e.ASSET_LIST_LOADED=`hlsAssetListLoaded`,e.INTERSTITIALS_UPDATED=`hlsInterstitialsUpdated`,e.INTERSTITIALS_BUFFERED_TO_BOUNDARY=`hlsInterstitialsBufferedToBoundary`,e.INTERSTITIAL_ASSET_PLAYER_CREATED=`hlsInterstitialAssetPlayerCreated`,e.INTERSTITIAL_STARTED=`hlsInterstitialStarted`,e.INTERSTITIAL_ASSET_STARTED=`hlsInterstitialAssetStarted`,e.INTERSTITIAL_ASSET_ENDED=`hlsInterstitialAssetEnded`,e.INTERSTITIAL_ASSET_ERROR=`hlsInterstitialAssetError`,e.INTERSTITIAL_ENDED=`hlsInterstitialEnded`,e.INTERSTITIALS_PRIMARY_RESUMED=`hlsInterstitialsPrimaryResumed`,e.PLAYOUT_LIMIT_REACHED=`hlsPlayoutLimitReached`,e.EVENT_CUE_ENTER=`hlsEventCueEnter`,e}({});function vt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var yt={exports:{}},bt;function xt(){return bt?yt.exports:(bt=1,(function(e,t){(function(t){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,n){if(n||={},e=e.trim(),t=t.trim(),!t){if(!n.alwaysNormalize)return e;var i=o.parseURL(e);if(!i)throw Error(`Error trying to parse base URL.`);return i.path=o.normalizePath(i.path),o.buildURLFromParts(i)}var a=o.parseURL(t);if(!a)throw Error(`Error trying to parse relative URL.`);if(a.scheme)return n.alwaysNormalize?(a.path=o.normalizePath(a.path),o.buildURLFromParts(a)):t;var s=o.parseURL(e);if(!s)throw Error(`Error trying to parse base URL.`);if(!s.netLoc&&s.path&&s.path[0]!==`/`){var c=r.exec(s.path);s.netLoc=c[1],s.path=c[2]}s.netLoc&&!s.path&&(s.path=`/`);var l={scheme:s.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(l.netLoc=s.netLoc,a.path[0]!==`/`)){if(!a.path)l.path=s.path,a.params||(l.params=s.params,a.query||(l.query=s.query));else{var u=s.path,d=u.substring(0,u.lastIndexOf(`/`)+1)+a.path;l.path=o.normalizePath(d)}}return l.path===null&&(l.path=n.alwaysNormalize?o.normalizePath(a.path):a.path),o.buildURLFromParts(l)},parseURL:function(e){var t=n.exec(e);return t?{scheme:t[1]||``,netLoc:t[2]||``,path:t[3]||``,params:t[4]||``,query:t[5]||``,fragment:t[6]||``}:null},normalizePath:function(e){for(e=e.split(``).reverse().join(``).replace(i,``);e.length!==(e=e.replace(a,``)).length;);return e.split(``).reverse().join(``)},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=o})()})(yt),yt.exports)}var St=xt(),Ct=class{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},R=function(e){return e.MANIFEST=`manifest`,e.LEVEL=`level`,e.AUDIO_TRACK=`audioTrack`,e.SUBTITLE_TRACK=`subtitleTrack`,e.MEDIA_FRAGMENT=`media-fragment`,e.KEY=`key`,e.STEERING_MANIFEST=`steering-manifest`,e.SERVER_CERTIFICATE=`server-certificate`,e.INTERSTITIAL_ASSET_LIST=`interstitial-asset-list`,e}({}),z=function(e){return e.MAIN=`main`,e.AUDIO=`audio`,e.SUBTITLE=`subtitle`,e}({}),B={AUDIO:`audio`,VIDEO:`video`,AUDIOVIDEO:`audiovideo`},wt=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e==`string`&&(e={url:e}),this.base=e,jt(this,`stats`)}setByteRange(e,t){let n=e.split(`@`,2),r;r=n.length===1?t?.byteRangeEndOffset||0:parseInt(n[1]),this._byteRange=[r,parseInt(n[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[B.AUDIO]:null,[B.VIDEO]:null,[B.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Ct),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=St.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||``}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[B.AUDIO]=null,e[B.VIDEO]=null,e[B.AUDIOVIDEO]=null,this.url=null}};function Tt(e){return e.sn!==`initSegment`}function Et(e,t){return e.sn===t?.sn&&e.level===t.level}function Dt(e,t){return e.sn===t?.sn&&e.level===t.level&&e.cc===t.cc}var Ot=class extends wt{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(P(e)&&P(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||=t.identity.getDecryptData(this.sn);else if(!((e=this._decryptdata)!=null&&e.keyId)){let e=Object.keys(t);if(e.length===1){let n=this._decryptdata=t[e[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=P(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;let e=Object.keys(this.levelkeys),n=e.length;if(n>1||n===1&&(t=this.levelkeys[e[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!P(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Tt(this)?(this._ref||={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime},this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var n;let r=t[e];r&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,n,r,i,a=!1){let{elementaryStreams:o}=this,s=o[e];if(!s){o[e]={startPTS:t,endPTS:n,startDTS:r,endDTS:i,partial:a};return}s.startPTS=Math.min(s.startPTS,t),s.endPTS=Math.max(s.endPTS,n),s.startDTS=Math.min(s.startDTS,r),s.endDTS=Math.max(s.endDTS,i)}},kt=class extends wt{constructor(e,t,n,r,i){super(n),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint(`DURATION`),this.gap=e.bool(`GAP`),this.independent=e.bool(`INDEPENDENT`),this.relurl=e.enumeratedString(`URI`),this.fragment=t,this.index=r;let a=e.enumeratedString(`BYTERANGE`);a&&this.setByteRange(a,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===z.SUBTITLE&&this.stats.loading.end>0)}};function At(e,t){let n=Object.getPrototypeOf(e);if(n)return Object.getOwnPropertyDescriptor(n,t)||At(n,t)}function jt(e,t){let n=At(e,t);n&&(n.enumerable=!0,Object.defineProperty(e,t,n))}function Mt(e,t,n){return(t=Lt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function V(){return V=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},V.apply(null,arguments)}function Nt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function H(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Nt(Object(n),!0).forEach(function(t){Mt(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Nt(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Pt(e,t){if(e==null)return{};var n,r,i=Ft(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Ft(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function It(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Lt(e){var t=It(e,`string`);return typeof t==`symbol`?t:t+``}function Rt(e){switch(e.details){case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_TIMEOUT:case I.LEVEL_LOAD_TIMEOUT:case I.MANIFEST_LOAD_TIMEOUT:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.SUBTITLE_TRACK_LOAD_TIMEOUT:case I.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function zt(e){return e.details.startsWith(`key`)}function Bt(e){return zt(e)&&!!e.frag&&!e.frag.decryptdata}function Vt(e,t){let n=Rt(t);return e.default[`${n?`timeout`:`error`}Retry`]}function Ht(e,t){let n=e.backoff===`linear`?1:2**t;return Math.min(n*e.retryDelayMs,e.maxRetryDelayMs)}function Ut(e){return H(H({},e),{errorRetry:null,timeoutRetry:null})}function Wt(e,t,n,r){if(!e)return!1;let i=r?.code,a=t<e.maxNumRetry&&(Gt(i)||!!n);return e.shouldRetry?e.shouldRetry(e,t,n,r,a):a}function Gt(e){return Kt(e)||!!e&&(e<400||e>499)}function Kt(e){return e===0&&navigator.onLine===!1}function qt(e,t){return t>0&&e.loadError>0&&e.loadErrorTime!==0&&self.performance.now()-e.loadErrorTime>t}var Jt=class{constructor(e,t=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=n}sample(e,t){let n=this.alpha_**+e;this.estimate_=t*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-this.alpha_**+this.totalWeight_;if(e)return this.estimate_/e}return this.estimate_}},Yt=class{constructor(e,t,n,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Jt(e),this.fast_=new Jt(t),this.defaultTTFB_=r,this.ttfb_=new Jt(e)}update(e,t){let{slow_:n,fast_:r,ttfb_:i}=this;n.halfLife!==e&&(this.slow_=new Jt(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.fast_=new Jt(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new Jt(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){if(t<=0)return;let n=Math.min(this.minDelayMs_,t/1e5),r=8*t,i=Math.max(e,n)/1e3,a=r/i;this.fast_.sample(i,a),this.slow_.sample(i,a)}sampleTTFB(e){let t=e/1e3,n=Math.sqrt(2)*Math.exp(-(t**2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},Xt=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let n=`[${e}]:`;this.trace=Zt,this.debug=t.debug.bind(null,n),this.log=t.log.bind(null,n),this.warn=t.warn.bind(null,n),this.info=t.info.bind(null,n),this.error=t.error.bind(null,n)}},Zt=function(){},Qt={trace:Zt,debug:Zt,log:Zt,warn:Zt,info:Zt,error:Zt};function $t(){return V({},Qt)}function en(e,t){let n=self.console[e];return n?n.bind(self.console,`${t?`[`+t+`] `:``}[${e}] >`):Zt}function tn(e,t,n){return t[e]?t[e].bind(t):en(e,n)}var nn=$t();function rn(e,t,n){let r=$t();if(typeof console==`object`&&e===!0||typeof e==`object`){let i=[`debug`,`log`,`info`,`warn`,`error`];i.forEach(t=>{r[t]=tn(t,e,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.7.4`)}catch{return $t()}i.forEach(t=>{nn[t]=tn(t,e)})}else V(nn,r);return r}var U=nn;function an(e=!0){if(!(typeof self>`u`))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function on(e){return typeof self<`u`&&e===self.ManagedMediaSource}function sn(e,t){let n=Object.keys(e),r=Object.keys(t),i=n.length,a=r.length;return!i||!a||i===a&&!n.some(e=>r.indexOf(e)===-1)}function cn(e){return btoa(String.fromCharCode(...e))}function ln(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}var un=`utf-16`,dn=`utf-16be`,fn=`utf-16le`,pn=`utf-8`;function mn(e,t={}){let n;n=ln(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);let r=0,{encoding:i}=t;if(!i){let e=n.getUint8(0),t=n.getUint8(1);e==239&&t==187&&n.getUint8(2)==191?(i=pn,r=3):e==254&&t==255?(i=dn,r=2):e==255&&t==254?(i=fn,r=2):i=pn}if(typeof TextDecoder<`u`)return new TextDecoder(i).decode(n);let{byteLength:a}=n,o=i!==dn,s=``,c;for(;r<a;){switch(i){case pn:if(c=n.getUint8(r),c<128)r++;else if(c>=194&&c<=223){if(r+1<a){let e=n.getUint8(r+1);e>=128&&e<=191?(c=(c&31)<<6|e&63,r+=2):r++}else r++}else if(c>=224&&c<=239){if(r+2<=a-1){let e=n.getUint8(r+1),t=n.getUint8(r+2);e>=128&&e<=191&&t>=128&&t<=191?(c=(c&15)<<12|(e&63)<<6|t&63,r+=3):r++}else r++}else if(c>=240&&c<=244){if(r+3<=a-1){let e=n.getUint8(r+1),t=n.getUint8(r+2),i=n.getUint8(r+3);e>=128&&e<=191&&t>=128&&t<=191&&i>=128&&i<=191?(c=(c&7)<<18|(e&63)<<12|(t&63)<<6|i&63,r+=4):r++}else r++}else r++;break;case dn:case un:case fn:c=n.getUint16(r,o),r+=2}s+=String.fromCodePoint(c)}return s}function hn(e){let t=typeof e==`string`?new URL(e):e;return t.origin+t.pathname.substring(0,t.pathname.lastIndexOf(`/`)+1)}function gn(e,t){if(e<0)return-gn(-e,t);let n=10**t;if(Math.abs(e*n%1-.5)<2**-52){let t=Math.floor(e*n);return(t%2==0?t:t+1)/n}return Math.round(e*n)/n}function _n(e,t){let n;try{n=new URL(e)}catch{return e}let r=new URL(t);if(n.origin!==r.origin)return e;let i=n.pathname.split(`/`).slice(1),a=r.pathname.split(`/`).slice(1,-1),o=Math.min(i.length,a.length);for(let e=0;e<o&&i[e]===a[e];e++)i.shift(),a.shift();for(;a.length;)a.shift(),i.unshift(`..`);return i.join(`/`)+n.search+n.hash}function vn(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf(`/`)+1)}catch{let e=new Date().getTime();return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,t=>{let n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==`x`?n:n&3|8).toString(16)})}}}function yn(e,t){return t+10<=e.length&&e[t]===73&&e[t+1]===68&&e[t+2]===51&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function bn(e,t){let n=0;return n=(e[t]&127)<<21,n|=(e[t+1]&127)<<14,n|=(e[t+2]&127)<<7,n|=e[t+3]&127,n}function xn(e,t){return yn(e,t)&&bn(e,t+6)+10<=e.length-t}function Sn(e,t){return t+10<=e.length&&e[t]===51&&e[t+1]===68&&e[t+2]===73&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Cn(e,t){let n=t,r=0;for(;yn(e,t);){r+=10;let n=bn(e,t+6);r+=n,Sn(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(n,n+r)}function wn(e){return ln(e)?e:e.byteOffset==0&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function Tn(e,t=0,n=1/0){return En(e,t,n,Uint8Array)}function En(e,t,n,r){let i=Dn(e),a=1;`BYTES_PER_ELEMENT`in r&&(a=r.BYTES_PER_ELEMENT);let o=On(e)?e.byteOffset:0,s=(o+e.byteLength)/a,c=(o+t)/a,l=Math.floor(Math.max(0,Math.min(c,s)));return new r(i,l,Math.floor(Math.min(l+Math.max(n,0),s))-l)}function Dn(e){return ln(e)?e:e.buffer}function On(e){return e&&ln(e.buffer)&&e.byteLength!==void 0&&e.byteOffset!==void 0}function kn(e,t=!1){let n=t?e.indexOf(0):e.length,r=mn(new DataView(e.buffer,e.byteOffset,n),{encoding:pn});return t?r:r.replace(/\0/g,``)}function An(e){let t={key:e.type,description:``,data:``,mimeType:null,pictureType:null};if(e.size<2)return;if(e.data[0]!==3){console.log(`Ignore frame with unrecognized character encoding`);return}let n=e.data.subarray(1).indexOf(0);if(n===-1)return;let r=kn(Tn(e.data,1,n)),i=e.data[2+n],a=e.data.subarray(3+n).indexOf(0);if(a===-1)return;let o=kn(Tn(e.data,3+n,a)),s;return s=r===`-->`?kn(Tn(e.data,4+n+a)):wn(e.data.subarray(4+n+a)),t.mimeType=r,t.pictureType=i,t.description=o,t.data=s,t}function jn(e){if(e.size<2)return;let t=kn(e.data,!0),n=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:n.buffer}}function Mn(e){if(e.size<2)return;if(e.type===`TXXX`){let t=1,{data:n}=e,r=kn(n.subarray(t),!0);t+=r.length+1;let i=kn(n.subarray(t));return{key:e.type,info:r,data:i}}let t=kn(e.data.subarray(1));return{key:e.type,info:``,data:t}}function Nn(e){if(e.type===`WXXX`){if(e.size<2)return;let t=1,n=kn(e.data.subarray(t),!0);t+=n.length+1;let r=kn(e.data.subarray(t));return{key:e.type,info:n,data:r}}let t=kn(e.data);return{key:e.type,info:``,data:t}}function Pn(e){return e.type===`PRIV`?jn(e):e.type[0]===`W`?Nn(e):e.type===`APIC`?An(e):Mn(e)}function Fn(e){let t=String.fromCharCode(e[0],e[1],e[2],e[3]),n=bn(e,4);return{type:t,size:n,data:e.subarray(10,10+n)}}var In=10,Ln=10;function Rn(e){let t=0,n=[];for(;yn(e,t);){let r=bn(e,t+6);e[t+5]>>6&1&&(t+=In),t+=In;let i=t+r;for(;t+Ln<i;){let r=Fn(e.subarray(t)),i=Pn(r);i&&n.push(i),t+=r.size+In}Sn(e,t)&&(t+=In)}return n}function zn(e){return e&&e.key===`PRIV`&&e.info===`com.apple.streaming.transportStreamTimestamp`}function Bn(e){if(e.data.byteLength===8){let t=new Uint8Array(e.data),n=t[3]&1,r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,n&&(r+=47721858.84),Math.round(r)}}function Vn(e){let t=Rn(e);for(let e of t)if(zn(e))return Bn(e)}function Hn(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n].toString(16);r.length<2&&(r=`0`+r),t+=r}return t}function Un(e){return Uint8Array.from(e.replace(/^0x/,``).replace(/([\da-fA-F]{2}) ?/g,`0x$1 `).replace(/ +$/,``).split(` `)).buffer}function Wn(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function Gn(e){return String.fromCharCode.apply(null,e)}var Kn=2**32-1,W={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},qn={video:1,audio:2,id3:3,text:4};function Jn(e,t){let n=e[t]<<8|e[t+1];return n<0?65536+n:n}function G(e,t){let n=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return n<0?4294967296+n:n}function Yn(e,t){let n=G(e,t);return n*=2**32,n+=G(e,t+4),n}function Xn(e,t){let n=``;for(let r=t;r<e.length;r++)if(n+=String.fromCharCode(e[r]),e[r]===0)return n;return null}function Zn(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Qn(e,t,n){e[t]=n>>24,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255}function $n(e,t,n){let r=t.byteOffset-e.byteOffset-8,i=8+n,a=t.byteLength+8-i;a<8||(Qn(e,r,i),Qn(e,r+i,a),Qn(e,r+i+4,W.free))}function er(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function tr(e,t){t.sort((e,t)=>e[0]-t[0]);let n=t.reduce((e,[t,n])=>e+n-t,0),r=new Uint8Array(e.byteLength-n),i=0,a=0;for(let n=0;n<t.length;n++){let[o,s]=t[n];r.set(e.subarray(i,o),a),a+=o-i,i=s}return r.set(e.subarray(i),a),{result:r,dropped:n,droppedBefore:e=>t.reduce((t,[n,r])=>r<=e?t+r-n:t,0)}}function nr(e){let t=K(e,[`moov`]);if(t.length!==1||K(e,[`moof`]).length)return null;let n=e.byteOffset,r=[],i=[],a=!1,o=K(t[0],[`trak`]);for(let e=0;e<o.length;e++){let t=o[e],s=K(t,[`mdia`,`hdlr`])[0];if((s?Gn(s.subarray(8,12)):``)===`vide`){a=!0;continue}let c=K(t,[`tkhd`])[0];if(!c)return null;let l=c[0];i.push(G(c,l===0?12:20)),r.push(er(t,n))}if(!a||!r.length)return null;let s=K(t[0],[`mvex`])[0],c=0;if(s){let e=K(s,[`trex`]);for(let t=0;t<e.length;t++){let a=e[t];i.indexOf(G(a,4))!==-1&&(r.push(er(a,n)),c+=a.byteLength+8)}}let{result:l,dropped:u,droppedBefore:d}=tr(e,r);if(Qn(l,t[0].byteOffset-n-8,t[0].byteLength+8-u),s&&c){let e=s.byteOffset-n-8;Qn(l,e-d(e),s.byteLength+8-c)}return l}function rr(e,t,n,r,i){if(n<1)return null;let a=K(e,[`moof`]);if(a.length!==1)return null;let o=a[0],s=e.byteOffset,c=[],l=[],u=K(o,[`traf`]),d=!0;for(let e=0;e<u.length;e++){let n=u[e],r=K(n,[`tfhd`])[0];if(!r)return null;G(r,4)===t?(c.push(n),G(r,0)&131072||(d=!1)):l.push(er(n,s))}if(!c.length||l.length&&!d)return null;if(r!==void 0){let t=n;for(let n=0;n<c.length;n++){let r=c[n],i=0,a=K(r,[`trun`]);for(let n=0;n<a.length;n++){let r=a[n],o=Math.min(t,G(r,4));if(o){Qn(e,r.byteOffset-s+4,o);let t=G(r,0)&16777215,n=(t&256?4:0)+(t&512?4:0)+(t&1024?4:0)+(t&2048?4:0);$n(e,r,8+(t&1?4:0)+(t&4?4:0)+o*n)}else Qn(e,r.byteOffset-s-4,W.free);t-=o,i+=o}let o=K(r,[`senc`])[0];o&&Qn(e,o.byteOffset-s+4,i);let l=K(r,[`saiz`])[0];if(l){let t=l[1]<<16|l[2]<<8|l[3],n=4;t&1&&(n+=8);let r=l[n];n+=1,Qn(e,l.byteOffset-s+n,i),$n(e,l,n+4+(r===0?i:0))}}let i=K(e,[`mdat`]);if(i.length===1){let t=i[0].byteOffset-s-8;Qn(e,t,r-t)}}let f=e,p=0,m=()=>0;if(l.length){({result:f,dropped:p,droppedBefore:m}=tr(e,l)),Qn(f,o.byteOffset-s-8,o.byteLength+8-p);for(let e=0;e<c.length;e++){let t=c[e],n=m(t.byteOffset-s),r=K(t,[`trun`]);for(let e=0;e<r.length;e++){let t=r[e];G(t,0)&1&&Qn(f,t.byteOffset-s-n+8,G(t,8)-p)}if(n){let e=K(t,[`saio`]);for(let t=0;t<e.length;t++){let r=e[t],i=r[0]===0?4:8,a=G(r,0)&1?12:4,o=G(r,a);for(a+=4;o--;a+=i){let e=a+i-4;Qn(f,r.byteOffset-s-n+e,G(r,e)-n)}}}}}if(i){let{durationOffset:e,value:t}=i;Qn(f,e-m(e),t)}return r===void 0?f:f.subarray(0,r-p)}function ir(e,t){let n=e.byteLength;for(let r=0;r<n;){let i=G(e,r);if(i>8&&G(e,r+4)===W[t])return!0;r=i>1?r+i:n}return!1}function K(e,t){let n=[];return t.length&&ar(e,t,0,0,e.byteLength,n),n}function ar(e,t,n,r,i,a){let o=t[n];if(o?.length!==4)return;let s=o.charCodeAt(0),c=o.charCodeAt(1),l=o.charCodeAt(2),u=o.charCodeAt(3),d=t.length-1;for(let o=r;o<i;){let r=o+8<=i,f=o+4<=i?e[o]*16777216+(e[o+1]<<16|e[o+2]<<8|e[o+3]):G(e,o),p=f>1?o+f:i;if(r&&e[o+4]===s&&e[o+5]===c&&e[o+6]===l&&e[o+7]===u){let r=Math.min(p,i);n===d?a.push(e.subarray(o+8,r)):ar(e,t,n+1,o+8,r,a)}o=p}}function or(e){let t=[],n=e[0],r=8,i=G(e,r);r+=4;let a=0,o=0;n===0?(a=G(e,r),o=G(e,r+4),r+=8):(a=Yn(e,r),o=Yn(e,r+8),r+=16),r+=2;let s=e.length+o,c=Jn(e,r);r+=2;for(let n=0;n<c;n++){let n=r,a=G(e,n);n+=4;let o=a&2147483647;if((a&2147483648)>>>31==1)return U.warn(`SIDX has hierarchical references (not supported)`),null;let c=G(e,n);n+=4,t.push({referenceSize:o,subsegmentDuration:c,info:{duration:c/i,start:s,end:s+o-1}}),s+=o,n+=4,r=n}return{earliestPresentationTime:a,timescale:i,version:n,referencesCount:c,references:t}}function sr(e){let t=[],n=K(e,[`moov`,`trak`]);for(let e=0;e<n.length;e++){let r=n[e],i=K(r,[`tkhd`])[0];if(i){let e=i[0],n=G(i,e===0?12:20),a=K(r,[`mdia`,`mdhd`])[0];if(a){e=a[0];let i=G(a,e===0?12:20),o=K(r,[`mdia`,`hdlr`])[0];if(o){let e=Gn(o.subarray(8,12)),a={soun:B.AUDIO,vide:B.VIDEO}[e],s=K(r,[`mdia`,`minf`,`stbl`,`stsd`])[0],c=cr(s);a?(t[n]={timescale:i,type:a,stsd:c},t[a]=H({timescale:i,id:n},c)):t[n]={timescale:i,type:e,stsd:c}}}}}return K(e,[`moov`,`mvex`,`trex`]).forEach(e=>{let n=G(e,4),r=t[n];r&&(r.default={duration:G(e,12),sampleSize:G(e,16),flags:G(e,20)})}),t}function cr(e){let t=e.subarray(8),n=t.subarray(86),r=Gn(t.subarray(4,8)),i=r,a,o=r===`enca`||r===`encv`;o&&K(K(t,[r])[0].subarray(r===`enca`?28:78),[`sinf`]).forEach(e=>{let t=K(e,[`schm`])[0];if(t){let n=Gn(t.subarray(4,8));if(n===`cbcs`||n===`cenc`){let t=K(e,[`frma`])[0];t&&(i=Gn(t))}}});let s=i;switch(i){case`avc1`:case`avc2`:case`avc3`:case`avc4`:{let e=K(n,[`avcC`])[0];e&&e.length>3&&(i+=`.`+fr(e[1])+fr(e[2])+fr(e[3]),a=lr(s===`avc1`?`dva1`:`dvav`,n));break}case`mp4a`:{let e=K(t,[r])[0],n=K(e.subarray(28),[`esds`])[0];if(n&&n.length>7){let e=4;if(n[e++]!==3)break;e=dr(n,e),e+=2;let t=n[e++];if(t&128&&(e+=2),t&64&&(e+=n[e++]),n[e++]!==4)break;e=dr(n,e);let r=n[e++];if(r===64)i+=`.`+fr(r);else break;if(e+=12,n[e++]!==5)break;e=dr(n,e);let a=n[e++],o=(a&248)>>3;o===31&&(o+=1+((a&7)<<3)+((n[e]&224)>>5)),i+=`.`+o}break}case`hvc1`:case`hev1`:{let e=K(n,[`hvcC`])[0];if(e&&e.length>12){let t=e[1],n=[``,`A`,`B`,`C`][t>>6],r=t&31,a=G(e,2),o=(t&32)>>5?`H`:`L`,s=e[12],c=e.subarray(6,12);i+=`.`+n+r,i+=`.`+ur(a).toString(16).toUpperCase(),i+=`.`+o+s;let l=``;for(let e=c.length;e--;){let t=c[e];(t||l)&&(l=`.`+t.toString(16).toUpperCase()+l)}i+=l}a=lr(s==`hev1`?`dvhe`:`dvh1`,n);break}case`dvh1`:case`dvhe`:case`dvav`:case`dva1`:case`dav1`:i=lr(i,n)||i;break;case`vp09`:{let e=K(n,[`vpcC`])[0];if(e&&e.length>6){let t=e[4],n=e[5],r=e[6]>>4&15;i+=`.`+pr(t)+`.`+pr(n)+`.`+pr(r)}break}case`av01`:{let e=K(n,[`av1C`])[0];if(e&&e.length>2){let t=e[1]>>>5,r=e[1]&31,o=e[2]>>>7?`H`:`M`,s=(e[2]&64)>>6,c=(e[2]&32)>>5,l=t===2&&s?c?12:10:s?10:8,u=(e[2]&16)>>4,d=(e[2]&8)>>3,f=(e[2]&4)>>2,p=e[2]&3;i+=`.`+t+`.`+pr(r)+o+`.`+pr(l)+`.`+u+`.`+d+f+p+`.`+pr(1)+`.`+pr(1)+`.`+pr(1)+`.0`,a=lr(`dav1`,n)}break}}return{codec:i,encrypted:o,supplemental:a}}function lr(e,t){let n=K(t,[`dvvC`]),r=n.length?n[0]:K(t,[`dvcC`])[0];if(r){let t=r[2]>>1&127,n=r[2]<<5&32|r[3]>>3&31;return e+`.`+pr(t)+`.`+pr(n)}}function ur(e){let t=0;for(let n=0;n<32;n++)t|=(e>>n&1)<<31-n;return t>>>0}function dr(e,t){let n=t+5;for(;e[t++]&128&&t<n;);return t}function fr(e){return(`0`+e.toString(16).toUpperCase()).slice(-2)}function pr(e){return(e<10?`0`:``)+e}function mr(e,t){if(!e||!t)return;let n=t.keyId;n?.byteLength===16&&t.isCommonEncryption&&gr(e,(e,t)=>{let r=e.subarray(8,24);r.some(e=>e!==0)||(U.log(`[eme] Patching keyId in 'enc${t?`a`:`v`}>sinf>>tenc' box: ${Hn(r)} -> ${Hn(n)}`),e.set(n,8))})}function hr(e){let t=[];return gr(e,e=>t.push(e.subarray(8,24))),t}function gr(e,t){K(e,[`moov`,`trak`]).forEach(e=>{let n=K(e,[`mdia`,`minf`,`stbl`,`stsd`])[0];if(!n)return;let r=n.subarray(8),i=K(r,[`enca`]),a=i.length>0;a||(i=K(r,[`encv`])),i.forEach(e=>{K(a?e.subarray(28):e.subarray(78),[`sinf`]).forEach(e=>{let n=_r(e);n&&t(n,a)})})})}function _r(e){let t=K(e,[`schm`])[0];if(t){let n=Gn(t.subarray(4,8));if(n===`cbcs`||n===`cenc`){let t=K(e,[`schi`,`tenc`])[0];if(t)return t}}}var vr;function yr(e){return typeof TextDecoder>`u`?kn(e):(vr||=new TextDecoder(`utf-8`)).decode(e).replace(/\0/g,``)}function br(e){let t=e.byteLength,n=[];for(let r=0;r<t;){let i=r+8<=t,a=r+4<=t?e[r]*16777216+(e[r+1]<<16|e[r+2]<<8|e[r+3]):G(e,r),o=a>1?r+a:t;if(i&&e[r+4]===109&&e[r+5]===111&&e[r+6]===111&&e[r+7]===102){let i=Math.min(o,t);for(let t=r+8;t<i;){let a=t+8<=i,o=t+4<=i?e[t]*16777216+(e[t+1]<<16|e[t+2]<<8|e[t+3]):G(e,t),s=o>1?t+o:i;if(a&&e[t+4]===116&&e[t+5]===114&&e[t+6]===97&&e[t+7]===102){let a=Math.min(s,i),o,c,l=[];for(let n=t+8;n<a;){let t=n+8<=a,r=n+4<=a?e[n]*16777216+(e[n+1]<<16|e[n+2]<<8|e[n+3]):G(e,n),i=r>1?n+r:a;if(t&&e[n+4]===116){let t=Math.min(i,a);e[n+5]===102&&e[n+6]===104&&e[n+7]===100?c||=e.subarray(n+8,t):e[n+5]===102&&e[n+6]===100&&e[n+7]===116?o||=e.subarray(n+8,t):e[n+5]===114&&e[n+6]===117&&e[n+7]===110&&l.push(e.subarray(n+8,t))}n=i}n.push({moofOffset:e.byteOffset+r,tfdt:o,tfhd:c,truns:l})}t=s}}r=o}return n}function xr(e,t,n,r,i=!0){return Cr(e,t,r,i)}function Sr(e,t,n,r,i=!1){let a=[],o=t.samples;return{samples:a,sampleData:{includeSampleDetails:i,tracks:Cr(o,n,r,i,{isHEVCFlavor:Dr(t.codec),samples:a,timeOffset:e,timescale:t.timescale,trackId:t.id})}}}function Cr(e,t,n,r,i){let a={},o=!1,s=br(e),c=e.byteLength;for(let l=0;l<s.length;l++){let{moofOffset:u,tfdt:d,tfhd:f,truns:p}=s[l],m=G(f,4),h=t[m];if(!h)continue;let g=a[m]||(a[m]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:h.timescale,type:h.type}),_;if(d){let e=d[0];_=G(d,4),e===1&&(_===Kn?n.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`):(_*=Kn+1,_+=G(d,8))),P(_)&&(!P(g.start)||_<g.start)&&(g.start=_),i&&P(_)&&(i.timeOffset=_/i.timescale)}let v=i?.trackId===m&&h.type===B.VIDEO,y=h.default,b=G(f,0)&16777215,x=y?.duration||0,S,C=y?.sampleSize||0,w=8;b&1&&(w+=8),b&2&&(w+=4),b&8&&(x=G(f,w),S=f.byteOffset-e.byteOffset+w,w+=4),b&16&&(C=G(f,w));let T=0,E=!!(b&1),D=!E&&!!(b&131072);E?(T=G(f,8),T*=2**32,T+=G(f,12)):D&&(T=u);let O=_||0,k=0,A=x;for(let t=0;t<p.length;t++){let n=p[t],a=G(n,4),o=g.sampleCount;g.sampleCount+=a;let s=n[3]&1,l=0,u=n[3]&4,d=n[2]&1,f=n[2]&2,m=n[2]&4,h=n[2]&8,_=8;s&&(l=Zn(n,_),_+=4),u&&(!(n[_+1]&1)&&g.keyFrameIndex===void 0&&(g.keyFrameIndex=o),_+=4);let y=T+l;if(!r&&n[1]===0&&n[2]===6&&n[3]===1){let t=O,r=y,o=_,s=-1,l=0,u=0,d=i?.timeOffset??0,f=x/(i?.timescale??1),p=i?.isHEVCFlavor===!0,m=p?2:1;for(let t=0;t<a;t++){let r=n[_]===0?n[_+1]<<16|n[_+2]<<8|n[_+3]:G(n,_),a=s===-1&&g.keyFrameIndex===void 0&&!(n[_+5]&1);_+=8;let o=y+r;if(v){if(r>0){let t=y;do{let n=e[t]===0?e[t+1]<<16|e[t+2]<<8|e[t+3]:G(e,t);t+=4;let r=e[t],a=p?r>>1&63:r&31;(p?a===39||a===40:a===6)&&kr(e.subarray(t,t+n),m,d,i.samples),t+=n}while(t<o)}d+=f}y=o,a&&(s=t,l=y)}if(y<=c)u=a;else{let e=r,t=o;for(let r=0;r<a;r++){let i=n[t]===0?n[t+1]<<16|n[t+2]<<8|n[t+3]:G(n,t);if(e+=i,e>c)break;u=r+1,t+=8}}if(v&&(i.timeOffset=d),s!==-1&&l<=c&&g.keyFrameIndex===void 0&&(g.keyFrameIndex=s,g.keyFrameStart=t+s*x),u){(!P(g.ptsMin)||t<g.ptsMin)&&(g.ptsMin=t);let e=t+u*x;(!P(g.ptsMax)||e>g.ptsMax)&&(g.ptsMax=e)}let h=x*a;O=t+h,k+=h;continue}let b,w;r&&(b=[],w={sampleOffset:y,samples:b,defaultSampleDurationOffset:S},y<=c&&g.trun.push(w));let E;for(let t=0;t<a;t++){let a;d?(r&&(a=n.byteOffset-e.byteOffset+_),A=G(n,_),_+=4):A=x,f?(E=G(n,_),_+=4):E=C;let o,s;m&&(s=n[_+1]&1?1:0,r&&(o={isNonSync:s,dependsOn:(n[_]&3)==1?1:2}),_+=4);let l=0;if(h&&(l=n[0]===0?G(n,_):Zn(n,_),_+=4),v){let t=y,n=0;for(;n<E;){let r=G(e,t);t+=4,Or(i.isHEVCFlavor,e[t])&&kr(e.subarray(t,t+r),i.isHEVCFlavor?2:1,i.timeOffset+l/i.timescale,i.samples),t+=r,n+=r+4}i.timeOffset+=A/i.timescale}if(y+=E,y<=c){w&&a!==void 0&&(w.lastSampleDurationOffset=a),s===0&&g.keyFrameIndex===void 0&&(g.keyFrameIndex=t,g.keyFrameStart=O);let e=O+l;(!P(g.ptsMin)||e<g.ptsMin)&&(g.ptsMin=e),(!P(g.ptsMax)||e+A>g.ptsMax)&&(g.ptsMax=e+A),b&&(b[t]={cts:l,duration:A,flags:o,size:E})}O+=A,k+=A}!k&&x&&(k+=x*a)}g.duration+=k,g.duration&&(o=!0)}if(!o){let t=1/0,n=0,r=K(e,[`sidx`]);for(let e=0;e<r.length;e++){let i=or(r[e]);if(i!=null&&i.references){t=Math.min(t,i.earliestPresentationTime/i.timescale);let e=i.references.reduce((e,t)=>e+t.info.duration||0,0);n=Math.max(n,e+i.earliestPresentationTime/i.timescale)}}n&&P(n)&&Object.keys(a).forEach(e=>{a[e].duration||(a[e].duration=n*a[e].timescale-a[e].start)})}return a}function wr(e){let t={valid:null,remainder:null},n=K(e,[`moof`]);if(n.length<2)return t.remainder=e,t;let r=n[n.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}function Tr(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function Er(e,t){let n=[],r=t.samples,i=t.timescale,a=t.id,o=!1;return K(r,[`moof`]).map(s=>{let c=s.byteOffset-8;K(s,[`traf`]).map(s=>{let l=K(s,[`tfdt`]).map(e=>{let t=e[0],n=G(e,4);return t===1&&(n*=2**32,n+=G(e,8)),n/i})[0];return l!==void 0&&(e=l),K(s,[`tfhd`]).map(l=>{let u=G(l,4),d=G(l,0)&16777215,f=!!(d&1),p=0,m=!!(d&2),h=!!(d&8),g=0,_=!!(d&16),v=0,y=!!(d&32),b=!f&&!!(d&131072),x=8;u===a&&(f?(p=G(l,x),x+=4,p*=2**32,p+=G(l,x),x+=4):b&&(p=c),m&&(x+=4),h&&(g=G(l,x),x+=4),_&&(v=G(l,x),x+=4),y&&(x+=4),t.type===`video`&&(o=Dr(t.codec)),K(s,[`trun`]).map(a=>{let s=a[0],c=G(a,0)&16777215,l=!!(c&1),u=0,d=!!(c&4),f=!!(c&256),m=0,h=!!(c&512),_=0,y=!!(c&1024),b=!!(c&2048),x=0,S=G(a,4),C=8;l&&(u=G(a,C),C+=4),d&&(C+=4);let w=p+u;for(let c=0;c<S;c++){if(f?(m=G(a,C),C+=4):m=g,h?(_=G(a,C),C+=4):_=v,y&&(C+=4),b&&(x=s===0?G(a,C):Zn(a,C),C+=4),t.type===B.VIDEO){let t=0;for(;t<_;){let a=G(r,w);w+=4,Or(o,r[w])&&kr(r.subarray(w,w+a),o?2:1,e+x/i,n),w+=a,t+=a+4}}e+=m/i}}))})})}),n}function Dr(e){if(!e)return!1;let t=e.substring(0,4);return t===`hvc1`||t===`hev1`||t===`dvh1`||t===`dvhe`}function Or(e,t){if(e){let e=t>>1&63;return e===39||e===40}return(t&31)==6}function kr(e,t,n,r){let i=Ar(e),a=0;a+=t;let o=0,s=0,c=0;for(;a<i.length;){o=0;do{if(a>=i.length)break;c=i[a++],o+=c}while(c===255);s=0;do{if(a>=i.length)break;c=i[a++],s+=c}while(c===255);let e=i.length-a,t=a;if(s<e)a+=s;else if(s>e){U.error(`Malformed SEI payload. ${s} is too small, only ${e} bytes left to parse.`);break}if(o===4){if(i[t++]===181){let e=Jn(i,t);if(t+=2,e===49){let e=G(i,t);if(t+=4,e===1195456820){let e=i[t++];if(e===3){let a=i[t++],s=31&a,c=64&a,l=c?2+s*3:0,u=new Uint8Array(l);if(c){u[0]=a;for(let e=1;e<l;e++)u[e]=i[t++]}r.push({type:e,payloadType:o,pts:n,bytes:u})}}}}}else if(o===5&&s>16){let e=[];for(let n=0;n<16;n++){let r=i[t++].toString(16);e.push(r.length==1?`0`+r:r),(n===3||n===5||n===7||n===9)&&e.push(`-`)}let a=s-16,c=new Uint8Array(a);for(let e=0;e<a;e++)c[e]=i[t++];r.push({payloadType:o,pts:n,uuid:e.join(``),userData:yr(c),userDataBytes:c})}}}function Ar(e){let t=e.byteLength,n,r=e.indexOf(3,3);for(;r!==-1;)e[r-1]===0&&e[r-2]===0&&(n||=[]).push(r),r=e.indexOf(3,r+1);if(!n)return e;let i=t-n.length,a=new Uint8Array(i),o=0,s=0;for(let t=0;t<i;s++,t++)s===n[o]&&(s++,o++),a[t]=e[s];return a}function jr(e){let t=e[0],n=``,r=``,i=0,a=0,o,s=0,c=0,l=4;if(t===0){let t=Xn(e,l),o=t===null?null:Xn(e,l+t.length);t!==null&&o!==null?(n=t,r=o,l+=t.length+o.length,i=G(e,l),l+=4,a=G(e,l),l+=4,s=G(e,l),l+=4,c=G(e,l),l+=4):(U.warn(`Unterminated ${t===null?`scheme_id_uri`:`value`} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),l=e.length)}else if(t===1){i=G(e,l),l+=4;let t=G(e,l);l+=4;let a=G(e,l);l+=4,o=2**32*t+a,gt(o)||(o=2**53-1,U.warn(`Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box`)),s=G(e,l),l+=4,c=G(e,l),l+=4;let u=Xn(e,l),d=u===null?null:Xn(e,l+u.length);u!==null&&(n=u,l+=u.length),d===null?(U.warn(`Unterminated ${u===null?`scheme_id_uri`:`value`} in parsing emsg box: version 1 box ends inside a string, dropping its ${u===null?`strings and payload`:`value and payload`}`),l=e.length):(r=d,l+=d.length)}let u=e.subarray(l,e.byteLength);return{schemeIdUri:n,value:r,timeScale:i,presentationTime:o,presentationTimeDelta:a,eventDuration:s,id:c,payload:u}}function Mr(e,...t){let n=t.length,r=8,i=n;for(;i--;)r+=t[i].byteLength;let a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=r&255,a.set(e,4),i=0,r=8;i<n;i++)a.set(t[i],r),r+=t[i].byteLength;return a}function Nr(e,t,n){if(e.byteLength!==16)throw RangeError(`Invalid system id`);let r,i;r=0,i=new Uint8Array;let a;r>0?(a=new Uint8Array(4),t.length>0&&new DataView(a.buffer).setUint32(0,t.length,!1)):a=new Uint8Array;let o=new Uint8Array(4);return n.byteLength>0&&new DataView(o.buffer).setUint32(0,n.byteLength,!1),Mr([112,115,115,104],new Uint8Array([r,0,0,0]),e,a,i,o,n)}function Pr(e){let t=[];if(e instanceof ArrayBuffer){let n=e.byteLength,r=0;for(;r+32<n;){let n=Ir(new DataView(e,r));t.push(n),r+=n.size}}return t}function Fr(e){let t=[];for(let n=0;n<e.length;){let r=e[n++],i=r&7;if(i===0){for(;e[n++]&128;);continue}if(i!==2){n+=i===1?8:4;continue}let a=0;for(let t=0,r=128;r&128;t+=7)a|=((r=e[n++])&127)<<t;if(r>>3==2){if(a===32){let r=new Uint8Array(16);for(let t=0;t<16;t++)r[t]=parseInt(String.fromCharCode(e[n+t*2],e[n+t*2+1]),16);t.push(r)}else a===16&&t.push(e.subarray(n,n+16))}n+=a}return t}function Ir(e){let t=e.getUint32(0),n=e.byteOffset,r=e.byteLength;if(r<t)return{offset:n,size:r};if(e.getUint32(4)!==1886614376)return{offset:n,size:t};let i=e.getUint32(8)>>>24;if(i!==0&&i!==1)return{offset:n,size:t};let a=e.buffer,o=Hn(new Uint8Array(a,n+12,16)),s=null,c=null,l=0;if(i===0)l=28;else{let i=e.getUint32(28);if(!i||r<32+i*16)return{offset:n,size:t};s=[];for(let e=0;e<i;e++)s.push(new Uint8Array(a,n+32+e*16,16));l=32+i*16}if(!l)return{offset:n,size:t};let u=e.getUint32(l);return t-32<u?{offset:n,size:t}:(c=new Uint8Array(a,n+l+4,u),i===0&&(s=Fr(c)),{version:i,systemId:o,kids:s,data:c,offset:n,size:t})}var Lr=Hr(`userAgent`),Rr=Hr(`vendor`),zr,Br,Vr;function Hr(e){try{return navigator[e]||``}catch{}return``}function Ur(){if(Vr===void 0){let e=Lr.match(/Safari\/(\d+)/i);Vr=e?parseInt(e[1]):0}return Vr}function Wr(){if(zr===void 0){let e=Lr.match(/Chrome\/(\d+)/i);zr=e?parseInt(e[1]):0}return zr}function Gr(){if(Br===void 0){let e=Lr.match(/Firefox\/(\d+)/i);Br=e?parseInt(e[1]):0}return Br}function Kr(){return/\(Windows.+Firefox\//i.test(Lr)}function qr(){return Rr.indexOf(`Apple`)>-1||/iPhone|iPad|iPod/.test(Lr)}function Jr(){return/Android/.test(Lr)}var Yr={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function Xr(e,t){let n=Yr[t];return!!n&&!!n[e.slice(0,4)]}function Zr(e,t,n=!0){return!e.split(`,`).some(e=>!Qr(e,t,n))}function Qr(e,t,n=!0){return an(n)?.isTypeSupported($r(e,t))??!1}function $r(e,t){return`${t}/mp4;codecs=${e}`}function ei(e){if(e){let t=e.substring(0,4);return Yr.video[t]}return 2}function ti(e){let t=Kr();return e.split(`,`).reduce((e,n)=>{let r=t&&Dr(n)?9:Yr.video[n];return r?(r*2+e)/(e?3:2):(Yr.audio[n]+e)/(e?2:1)},0)}var ni={};function ri(e,t=!0){if(ni[e])return ni[e];let n={flac:[`flac`,`fLaC`,`FLAC`],opus:[`opus`,`Opus`],"mp4a.40.34":[`mp3`]}[e];for(let i=0;i<n.length;i++){var r;if(Qr(n[i],`audio`,t))return ni[e]=n[i],n[i];if(n[i]===`mp3`&&(r=an(t))!=null&&r.isTypeSupported(`audio/mpeg`))return``}return e}var ii=/flac|opus|mp4a\.40\.34/i;function ai(e,t=!0){return e.replace(ii,e=>ri(e.toLowerCase(),t))}function oi(e,t){let n=[];if(e){let t=e.split(`,`);for(let e=0;e<t.length;e++)Xr(t[e],`video`)||n.push(t[e])}return t&&n.push(t),n.join(`,`)}function si(e,t){if(e&&(e.length>4||[`ac-3`,`ec-3`,`alac`,`fLaC`,`Opus`].indexOf(e)!==-1)&&(ci(e,`audio`)||ci(e,`video`)))return e;if(t){let n=t.split(`,`);if(n.length>1){if(e){for(let t=n.length;t--;)if(n[t].substring(0,4)===e.substring(0,4))return n[t]}return n[0]}}return t||e}function ci(e,t){return Xr(e,t)&&Qr(e,t)}function li(e){let t=e.split(`,`);for(let e=0;e<t.length;e++){let n=t[e].split(`.`);n.length>2&&n[0]===`avc1`&&(t[e]=`avc1.${parseInt(n[1]).toString(16)}${(`000`+parseInt(n[2]).toString(16)).slice(-4)}`)}return t.join(`,`)}function ui(e){if(e.startsWith(`av01.`)){let t=e.split(`.`),n=[`0`,`111`,`01`,`01`,`01`,`0`];for(let e=t.length;e>4&&e<10;e++)t[e]=n[e-4];return t.join(`.`)}return e}function di(e){let t=an(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported(`audio/mpeg`),mp3:t.isTypeSupported(`audio/mp4; codecs="mp3"`),ac3:t.isTypeSupported(`audio/mp4; codecs="ac-3"`)}}function fi(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,`$1`)}var pi={supported:!0,powerEfficient:!0,smooth:!0},mi={supported:!1,smooth:!1,powerEfficient:!1},hi={supported:!0,configurations:[],decodingInfoResults:[pi]};function gi(e,t){return{supported:!1,configurations:t,decodingInfoResults:[mi],error:e}}function _i(e,t,n,r,i,a){let o=e.videoCodec,s=e.audioCodec?e.audioGroups:null,c=a?.audioCodec,l=a?.channels,u=l?parseInt(l):c?1/0:2,d=null;if(s!=null&&s.length)try{d=s.length===1&&s[0]?t.groups[s[0]].channels:s.reduce((e,n)=>{if(n){let r=t.groups[n];if(!r)throw Error(`Audio track group ${n} not found`);Object.keys(r.channels).forEach(t=>{e[t]=(e[t]||0)+r.channels[t]})}return e},{2:0})}catch{return!0}return o!==void 0&&(o.split(`,`).some(e=>Dr(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||e.videoRange!==`SDR`&&e.videoRange!==n||e.bitrate>Math.max(i,8e6))||!!d&&P(u)&&Object.keys(d).some(e=>parseInt(e)>u)}function vi(e,t,n,r={}){let i=e.videoCodec;if(!i&&!e.audioCodec||!n)return Promise.resolve(hi);let a=[],o=yi(e),s=o.length,c=bi(e,t,s>0),l=c.length;for(let e=s||1*l||1;e--;){let t={type:`media-source`};if(s&&(t.video=o[e%s]),l){t.audio=c[e%l];let n=t.audio.bitrate;t.video&&n&&(t.video.bitrate-=n)}a.push(t)}if(i){let e=navigator.userAgent;if(i.split(`,`).some(e=>Dr(e))&&Kr())return Promise.resolve(gi(Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),a))}return Promise.all(a.map(e=>{let t=Ci(e);return r[t]||(r[t]=n.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:a,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:a,decodingInfoResults:[],error:e}))}function yi(e){let t=e.videoCodec?.split(`,`),n=Si(e),r=e.width||640,i=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return t?t.map(e=>{let t={contentType:$r(ui(e),`video`),width:r,height:i,bitrate:n,framerate:a};return o!==`sdr`&&(t.transferFunction=o),t}):[]}function bi(e,t,n){let r=e.audioCodec?.split(`,`),i=Si(e);return r&&e.audioGroups?e.audioGroups.reduce((e,a)=>{let o=a?t.groups[a]?.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===a){let a=parseFloat(t.channels||``);r.forEach(t=>{let r={contentType:$r(t,`audio`),bitrate:n?xi(t,i):i};a&&(r.channels=``+a),e.push(r)})}return e},e):e},[]):[]}function xi(e,t){if(t<=1)return 1;let n=128e3;return e===`ec-3`?n=768e3:e===`ac-3`&&(n=64e4),Math.min(t/2,n)}function Si(e){return Math.ceil(Math.max(e.bitrate*.9,e.averageBitrate)/1e3)*1e3||1}function Ci(e){let t=``,{audio:n,video:r}=e;if(r){let e=fi(r.contentType);t+=`${e}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||`sd`}_${Math.ceil(r.bitrate/1e5)}`}if(n){let e=fi(n.contentType);t+=`${r?`_`:``}${e}_c${n.channels}`}return t}function wi(e,t,n){let r=encodeURIComponent(t),i=`${r}=${encodeURIComponent(n)}`,a=!1,o=[];e.search.substring(1).split(`&`).forEach(e=>{e===r||e.startsWith(r+`=`)?a||=(o.push(i),!0):e&&o.push(e)}),a||o.push(i),e.search=o.join(`&`)}var Ti=[`NONE`,`TYPE-0`,`TYPE-1`,null];function Ei(e){return Ti.indexOf(e)>-1}var Di=[`SDR`,`PQ`,`HLG`];function Oi(e){return!!e&&Di.indexOf(e)>-1}var ki={No:``,Yes:`YES`,v2:`v2`};function Ai(e){let{canSkipUntil:t,canSkipDateRanges:n,age:r}=e,i=r<t/2;return t&&i?n?ki.v2:ki.Yes:ki.No}var ji=class{constructor(e,t,n){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=n}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&wi(t,`_HLS_msn`,this.msn.toString()),this.part!==void 0&&wi(t,`_HLS_part`,this.part.toString()),this.skip&&wi(t,`_HLS_skip`,this.skip),t.href}},Mi=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat(`FRAME-RATE`,0),this._avgBitrate=e.attrs.decimalInteger(`AVERAGE-BANDWIDTH`),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,`imageCodec`in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(`,`),`supplemental`in e){this.supplemental=e.supplemental;let t=e.supplemental?.videoCodec;t&&t!==e.videoCodec&&(this.codecSet+=`,${t.substring(0,4)}`)}`iframes`in e&&e.iframes?this.iframes=!0:(this.addGroupId(`audio`,e.attrs.AUDIO),this.addGroupId(`text`,e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||``}get pathwayId(){return this.attrs[`PATHWAY-ID`]||`.`}get videoRange(){return this.attrs[`VIDEO-RANGE`]||`SDR`}get score(){return this.attrs.optionalFloat(`SCORE`,0)}get uri(){return this.url[0]||``}hasAudioGroup(e){return Ni(this._audioGroups,e)}hasSubtitleGroup(e){return Ni(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e===`audio`){let e=this._audioGroups;e||=this._audioGroups=[],e.indexOf(t)===-1&&e.push(t)}else if(e===`text`){let e=this._subtitleGroups;e||=this._subtitleGroups=[],e.indexOf(t)===-1&&e.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){return this.audioGroups?.[0]}get textGroupId(){return this.subtitleGroups?.[0]}addFallback(){}};function Ni(e,t){return!t||!e?!1:e.indexOf(t)!==-1}function Pi(){if(typeof matchMedia==`function`){let e=matchMedia(`(dynamic-range: high)`),t=matchMedia(`bad query`);if(e.media!==t.media)return e.matches===!0}return!1}function Fi(e,t){let n=!1,r=[];if(e&&(n=e!==`SDR`,r=[e]),t){r=t.allowedVideoRanges||Di.slice(0);let e=r.join(``)!==`SDR`&&!t.videoCodec;n=t.preferHDR===void 0?e&&Pi():t.preferHDR,n||(r=[`SDR`])}return{preferHDR:n,allowedVideoRanges:r}}var Ii=e=>{let t=new WeakSet;return(n,r)=>{if(e&&(r=e(n,r)),typeof r==`object`&&r){if(t.has(r))return;t.add(r)}return r}},q=(e,t)=>JSON.stringify(e,Ii(t));function Li(e,t,n,r,i){let a=Object.keys(e),o=r?.channels,s=r?.audioCodec,c=i?.videoCodec,l=o&&parseInt(o)===2,u=!1,d=!1,f=1/0,p=1/0,m=1/0,h=1/0,g=0,_=[],{preferHDR:v,allowedVideoRanges:y}=Fi(t,i);for(let t=a.length;t--;){let n=e[a[t]];u||=n.channels[2]>0,f=Math.min(f,n.minHeight),p=Math.min(p,n.minFramerate),m=Math.min(m,n.minBitrate),y.filter(e=>n.videoRanges[e]>0).length>0&&(d=!0)}f=P(f)?f:0,p=P(p)?p:0;let b=Math.max(1080,f),x=Math.max(30,p);m=P(m)?m:n,n=Math.max(m,n),d||(t=void 0);let S=a.length>1;return{codecSet:a.reduce((t,r)=>{let i=e[r];if(r===t)return t;if(_=d?y.filter(e=>i.videoRanges[e]>0):[],S){if(i.minBitrate>n)return Ri(r,`min bitrate of ${i.minBitrate} > current estimate of ${n}`),t;if(!i.hasDefaultAudio)return Ri(r,`no renditions with default or auto-select sound found`),t;if(s&&r.indexOf(s.substring(0,4))%5!=0)return Ri(r,`audio codec preference "${s}" not found`),t;if(o&&!l){if(!i.channels[o])return Ri(r,`no renditions with ${o} channel sound found (channels options: ${Object.keys(i.channels)})`),t}else if((!s||l)&&u&&i.channels[2]===0)return Ri(r,`no renditions with stereo sound found`),t;if(i.minHeight>b)return Ri(r,`min resolution of ${i.minHeight} > maximum of ${b}`),t;if(i.minFramerate>x)return Ri(r,`min framerate of ${i.minFramerate} > maximum of ${x}`),t;if(!_.some(e=>i.videoRanges[e]>0))return Ri(r,`no variants with VIDEO-RANGE of ${q(_)} found`),t;if(c&&r.indexOf(c.substring(0,4))%5!=0)return Ri(r,`video codec preference "${c}" not found`),t;if(i.maxScore<g)return Ri(r,`max score of ${i.maxScore} < selected max of ${g}`),t}return t&&(ti(r)>=ti(t)||i.fragmentError>e[t].fragmentError)?t:(h=i.minIndex,g=i.maxScore,r)},void 0),videoRanges:_,preferHDR:v,minFramerate:p,minBitrate:m,minIndex:h}}function Ri(e,t){U.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function zi(e){return e.reduce((e,t)=>{let n=e.groups[t.groupId];n||=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1},n.tracks.push(t);let r=t.channels||`2`;return n.channels[r]=(n.channels[r]||0)+1,n.hasDefault=n.hasDefault||t.default,n.hasAutoSelect=n.hasAutoSelect||t.autoselect,n.hasDefault&&(e.hasDefaultAudio=!0),n.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Bi(e,t,n,r){return e.slice(n,r+1).reduce((e,n,r)=>{if(!n.codecSet)return e;let i=n.audioGroups,a=e[n.codecSet];a||(e[n.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,n.bitrate);let o=Math.min(n.height,n.width);return a.minHeight=Math.min(a.minHeight,o),a.minFramerate=Math.min(a.minFramerate,n.frameRate),a.minIndex=Math.min(a.minIndex,r),a.maxScore=Math.max(a.maxScore,n.score),a.fragmentError+=n.fragmentError,a.videoRanges[n.videoRange]=(a.videoRanges[n.videoRange]||0)+1,i&&i.forEach(e=>{if(!e)return;let n=t.groups[e];n&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?n.hasDefault:n.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(n.channels).forEach(e=>{a.channels[e]=(a.channels[e]||0)+n.channels[e]}))}),e},{})}function Vi(e){if(!e)return e;let{lang:t,assocLang:n,characteristics:r,channels:i,audioCodec:a}=e;return{lang:t,assocLang:n,characteristics:r,channels:i,audioCodec:a}}function Hi(e,t,n){if(`attrs`in e){let n=t.indexOf(e);if(n!==-1)return n}for(let r=0;r<t.length;r++){let i=t[r];if(Ui(e,i,n))return r}return-1}function Ui(e,t,n){let{groupId:r,name:i,lang:a,assocLang:o,default:s}=e,c=e.forced;return(r===void 0||t.groupId===r)&&(i===void 0||t.name===i)&&(a===void 0||Wi(a,t.lang))&&(o===void 0||t.assocLang===o)&&(s===void 0||t.default===s)&&(c===void 0||t.forced===c)&&(!(`characteristics`in e)||Gi(e.characteristics||``,t.characteristics))&&(n===void 0||n(e,t))}function Wi(e,t=`--`){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function Gi(e,t=``){let n=e.split(`,`),r=t.split(`,`);return n.length===r.length&&!n.some(e=>r.indexOf(e)===-1)}function Ki(e,t){let{audioCodec:n,channels:r}=e;return(n===void 0||(t.audioCodec||``).substring(0,4)===n.substring(0,4))&&(r===void 0||r===(t.channels||`2`))}function qi(e,t,n,r,i){let a=t[r],o=t.reduce((e,t,n)=>{let r=t.uri;return(e[r]||(e[r]=[])).push(n),e},{})[a.uri];o.length>1&&(r=Math.max.apply(Math,o));let s=a.videoRange,c=a.frameRate,l=a.codecSet.substring(0,4),u=Ji(t,r,t=>{if(t.videoRange!==s||t.frameRate!==c||t.codecSet.substring(0,4)!==l)return!1;let r=t.audioGroups;return Hi(e,n.filter(e=>Xi(e.groupId,r)),i)>-1});return u>-1?u:Ji(t,r,t=>{let r=t.audioGroups;return Hi(e,n.filter(e=>Xi(e.groupId,r)),i)>-1})}function Ji(e,t,n){for(let r=t;r>-1;r--)if(n(e[r]))return r;for(let r=t+1;r<e.length;r++)if(n(e[r]))return r;return-1}function Yi(e,t){return!!e&&e!==t.loadLevelObj?.uri}function Xi(e,t){return!t||t.indexOf(e)!==-1}function Zi(e,t){if(t||e){let n=V({},t);return e&&(e.videoCodec&&(n.videoCodec=e.videoCodec),e.videoRange&&(n.allowedVideoRanges=[e.videoRange])),n}}var Qi=class extends Xt{constructor(e){super(`abr`,e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey=``,this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{let{fragCurrent:t,partCurrent:n,hls:r}=this;if(!r)return;let{autoLevelEnabled:i,media:a}=r;if(!t||!a)return;let o=performance.now(),s=n?n.stats:t.stats,c=n?n.duration:t.duration,l=o-s.loading.start,u=r.minAutoLevel,d=t.level,f=this._nextAutoLevel;if(s.aborted||s.loaded&&s.loaded===s.total||d<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!i)return;let p=f>-1&&f!==d,m=!!e||p;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;let h=r.mainForwardBufferInfo;if(!m&&h===null)return;let g=this.bwEstimator.getEstimateTTFB(),_=Math.abs(a.playbackRate);if(l<=Math.max(g,1e3*(c/(_*2))))return;let v=h?h.len/_:0,y=s.loading.first?s.loading.first-s.loading.start:-1,b=s.loaded&&y>-1,x=this.getBwEstimate(),S=r.levels,C=S[d],w=Math.max(s.loaded,Math.round(c*(t.bitrate||C.averageBitrate)/8)),T=b?l-y:l;T<1&&b&&(T=Math.min(l,s.loaded*8/x));let E=b?s.loaded*1e3/T:0,D=g/1e3,O=E?(w-s.loaded)/E:w*8/x+D;if(O<=v)return;let k=E?E*8:x,A=(e?.details||r.latestLevelDetails)?.live===!0,j=r.config.abrBandWidthUpFactor,M=1/0,N;for(N=d-1;N>u;N--){let e=S[N].maxBitrate,t=!S[N].details||A;if(M=this.getTimeToLoadFrag(D,k,c*e,t),M<Math.min(v,c+D))break}if(M>=O||M>c*10)return;b?this.bwEstimator.sample(l-Math.min(g,y),s.loaded):this.bwEstimator.sampleTTFB(l);let ee=S[N].maxBitrate;this.getBwEstimate()*j>ee&&(this.firstAutoFloor=Math.min(N,r.firstLevel),this.resetEstimator(ee));let te=this.findBestLevel(ee,u,N,0,v,1,1);te>-1&&(N=te),this.warn(`Fragment ${t.sn}${n?` part `+n.index:``} of level ${d} is loading too slowly;
|
|
4
4
|
Fragment duration: ${t.duration.toFixed(3)}
|
|
@@ -43,7 +43,7 @@ ${n.m3u8}`)}function ds(e,t,n=!0,r){let i=t.startSN+t.skippedSegments-e.startSN,
|
|
|
43
43
|
`):n}function Tf(e,t){return[].slice.call(e.childNodes).reduce((e,n,r)=>{var i;return n.nodeName===`br`&&r?e+`
|
|
44
44
|
`:(i=n.childNodes)!=null&&i.length?e+Tf(n,t):e+(t?n.textContent.replace(/\s+/g,` `):n.textContent)},``)}function Ef(e,t,n){let r=`http://www.w3.org/ns/ttml#styling`,i=null,a=[`displayAlign`,`textAlign`,`color`,`backgroundColor`,`fontSize`,`fontFamily`],o=e!=null&&e.hasAttribute(`style`)?e.getAttribute(`style`):null;return o&&n.hasOwnProperty(o)&&(i=n[o]),a.reduce((n,a)=>{let o=Df(t,r,a)||Df(e,r,a)||Df(i,r,a);return o&&(n[a]=o),n},{})}function Df(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function Of(e){return Error(`Could not parse ttml timestamp ${e}`)}function kf(e,t){if(!e)return null;if(_f.test(e))return Af(e,t);let n=nf(e);return n===null&&vf.test(e)&&(n=jf(e,t)),n}function Af(e,t){let n=_f.exec(e),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function jf(e,t){let n=vf.exec(e),r=Number(n[1]);switch(n[2]){case`h`:return r*3600;case`m`:return r*60;case`ms`:return r/1e3;case`f`:return r/t.frameRate;case`t`:return r/t.tickRate}return r}function Mf(e,t,n,r=``,i=`disabled`){let a=e.ownerDocument.createElement(`track`);return a.kind=t,a.label=n,r&&(a.srclang=r),a.src=`data:,WEBVTT`,a.track.mode=i,e.appendChild(a),a}function Nf(e){return e.forced&&qr()?`forced`:e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?`captions`:`subtitles`}function Pf(e,t){let n=e.mode;if(n===`disabled`&&(e.mode=`hidden`),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(n){U.debug(`[texttrack-utils]: ${n}`);try{let n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(e){U.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}n===`disabled`&&(e.mode=n)}function Ff(e,t,n,r){let i=e.mode;if(i===`disabled`&&(e.mode=`hidden`),e.cues&&e.cues.length>0){let i=Lf(e.cues,t,n);for(let t=0;t<i.length;t++)(!r||r(i[t]))&&e.removeCue(i[t])}i===`disabled`&&(e.mode=i)}function If(e,t){if(t<=e[0].startTime)return 0;let n=e.length-1;if(t>e[n].endTime)return-1;let r=0,i=n,a;for(;r<=i;)if(a=Math.floor((i+r)/2),t<e[a].startTime)i=a-1;else if(t>e[a].startTime&&r<n)r=a+1;else return a;return e[r].startTime-t<t-e[i].startTime?r:i}function Lf(e,t,n){let r=[],i=If(e,t);if(i>-1)for(let a=i,o=e.length;a<o;a++){let i=e[a];if(i.startTime>=t&&i.endTime<=n)r.push(i);else if(i.startTime>n)return r}return r}var Rf=class extends Nl{constructor(e){super(e,`subtitle-track-controller`),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,t=!1;if(this.currentTrack){let n=this.currentTrack.trackNode?.track.mode;n===`showing`?(e=this.trackId,t=!0):n===`hidden`&&(e=this.trackId)}if(!t)for(let t=0;t<this.tracksInGroup.length;t++){let n=this.tracksInGroup[t].trackNode?.track.mode;if(n===`showing`){e=t;break}e<0&&n===`hidden`&&(e=t)}e>-1&&(this._subtitleDisplay=this.tracksInGroup[e].trackNode?.track.mode===`showing`),this.setSubtitleTrack(e,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVEL_LOADING,this.onLevelLoading,this),e.off(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(L.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(e=>{e.trackNode||=Mf(this.media,Nf(e),e.name,e.lang)});let t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;t?.mode===`disabled`&&(t.mode=this._subtitleDisplay?`showing`:`hidden`)}onMediaAttached(e,t){let n=t.media;this.media=n;let r=this.trackId;this.queuedDefaultTrack>-1&&(r=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(r),this.createTracksInGroup(),this.useTextTrackPolling=!(n.textTracks&&`onchange`in n.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):n.textTracks.addEventListener(`change`,this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let n=this.media;if(!n)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener(`change`,this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!r&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(e=>{let t=e.trackNode;t&&(t.track.mode=`hidden`,t.remove(),e.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let n=t.subtitleGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n;let e=[];if(this.tracks.forEach(t=>{(t.textCodec===gf?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!n||n.indexOf(t.groupId)>-1?(t.id=e.length,e.push(t)):t.trackNode&&=(t.trackNode.remove(),void 0))}),e.length===this.tracksInGroup.length){let t=!1;for(let n=0;n<e.length;n++)if(e[n]!==this.tracksInGroup[n]){t=!0;break}if(!t)return}e.length&&this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=e,this.trackId=-1,this.currentTrack=null;let t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;let n=Hi(t,e);if(n>-1)i=e[n];else{let e=Hi(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${n?.join(`,`)}" group-id`),this.hls.trigger(L.SUBTITLE_TRACKS_UPDATED,a),this.setSubtitleTrack(r),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,n=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let i=t[r];if(!(n&&!i.default||!n&&!e)&&(!e||Ui(i,e)))return r}if(e){for(let n=0;n<t.length;n++){let r=t[n];if(Fl(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(Fl(e.attrs,r.attrs,[`LANGUAGE`]))return n}}return-1}onError(e,t){!t.fatal&&t.context&&t.context.type===R.SUBTITLE_TRACK&&t.context.id===this.trackId&&Xi(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let n=this.currentTrack;if(n&&Ui(e,n))return n;let r=Hi(e,this.tracksInGroup);if(r>-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r,!0),e}if(n)return null;{let n=Hi(e,t);if(n>-1)return t[n]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(L.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;let e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){let n=t===e?this._subtitleDisplay?`showing`:`hidden`:`disabled`,r=t.trackNode.track;r.mode!==n&&(r.mode=n)}})}setSubtitleTrack(e,t=!1){let n=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=n.length||!P(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let r=this.currentTrack,i=n[e]||null;if(this.trackId=e,this.currentTrack=i,t&&this.toggleTrackModes(),!i){r&&this.hls.trigger(L.SUBTITLE_TRACK_SWITCH,{id:e});return}let a=!!i.details&&!i.details.live;if(i===r&&a)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:``));let{id:o,groupId:s=``,name:c,type:l,url:u}=i;this.hls.trigger(L.SUBTITLE_TRACK_SWITCH,{id:o,groupId:s,name:c,type:l,url:u});let d=this.switchParams(i.url,r?.details,i.details);this.loadPlaylist(d)}},zf=2,Bf=100,Vf=class extends Za{constructor(e,t){super(`gap-controller`,e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;(e=this.media)!=null&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{this.hls&&(this.ended=this.media?.currentTime||1,this.hls.trigger(L.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Bf),this.mediaSource=t.mediaSource;let n=this.media=t.media;Y(n,`playing`,this.onMediaPlaying),Y(n,`waiting`,this.onMediaWaiting),Y(n,`ended`,this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:n}=this;n&&(X(n,`playing`,this.onMediaPlaying),X(n,`waiting`,this.onMediaWaiting),X(n,`ended`,this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){let e=this.hls?.config.timelineOffset||0;return this.media?Math.max(this.media.currentTime,e):e}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){let n=this.hls?.config;if(!n)return;let r=this.media;if(!r)return;let{seeking:i}=r,a=this.seeking&&!i,o=!this.seeking&&i,s=r.paused&&!i||r.ended||r.playbackRate===0;if(this.seeking=i,e!==t){t&&(this.ended=0),this.moved=!0,i||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!s&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(o||a){a&&this.stallResolved(e);return}if(s){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&r.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(L.MEDIA_ENDED,{stalled:!1}));return}if(!J.getBuffered(r).length){this.skipRetry=this.nudgeRetry=0;return}let c=J.bufferInfo(r,e,0),l=this.fragmentTracker;l&&this.hls&&Gf(c,e,l,this.hls);let u=c.nextStart||0;if(i&&l&&this.hls){let t=Hf(this.hls.inFlightFragments,e),n=c.len>zf,r=!u||t||u-e>zf&&!l.getPartialFragment(e);if(n||r)return;this.moved=!1}let d=this.hls?.latestLevelDetails;if(!this.moved&&this.stalled!==null&&l){if(!(c.len>0)&&!u)return;let t=Math.max(u,c.start||0)-e,n=d!=null&&d.live?d.targetduration*2:zf,i=Wf(e,l);if(t>0&&(t<=n||i)){r.paused||this._trySkipBufferHole(i);return}}let f=n.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting,h=this.stalled;if(h===null){if(m>0&&p-m<f)h=this.stalled=m;else{this.stalled=p;return}}let g=p-h;if(!i&&(g>=f||m&&this.moved)&&this.hls){if(this.mediaSource?.readyState===`ended`&&!(d!=null&&d.live)&&Math.abs(e-(d?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(L.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return;if(r.currentTime!==e){let t=e;e=r.currentTime,this.moved=!0,this.log(`currentTime changed ${t} > ${e}`);return}}let _=J.bufferInfo(r,e,n.maxBufferHole);this._tryFixBufferStall(_,g,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let n=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(L.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var n;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&r&&r.length>1&&e>r.end(0)){let n=J.bufferedInfo(J.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let n=J.timeRangesToArray(r),i=J.bufferedInfo(n,t,0).bufferedIndex;if(i>-1&&i<n.length-1){let t=J.bufferedInfo(n,e,0).bufferedIndex,r=n[i].end,a=n[i+1].start;if((t===-1||t>i)&&a-r<1&&e-r<2){let n=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${a} buffered index: ${t}`);this.warn(n.message),this.media.currentTime+=1e-6;let i=Wf(e,this.fragmentTracker);i&&`fragment`in i?i=i.fragment:i||=void 0;let o=J.bufferInfo(this.media,e,0);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:n,reason:n.message,frag:i,buffer:o.len,bufferInfo:o})}}}}}_tryFixBufferStall(e,t,n){let{fragmentTracker:r,media:i}=this,a=this.hls?.config;if(!i||!r||!a)return;let o=this.hls?.latestLevelDetails,s=Wf(n,r);if((s||o!=null&&o.live&&n<o.fragmentStart)&&(this._trySkipBufferHole(s)||!this.media))return;let c=e.buffered,l=this.adjacentTraversal(e,n);(c&&c.length>1&&e.len>a.maxBufferHole||e.nextStart&&(e.nextStart-n<a.maxBufferHole||l))&&(t>a.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn(`Trying to nudge playhead over buffer-hole`),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let n=this.fragmentTracker,r=e.nextStart;if(n&&r){let e=n.getFragAtPos(t,z.MAIN),i=n.getFragAtPos(r,z.MAIN);if(e&&i)return i.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:n,stallReported:r,stalled:i}=this;if(!r&&i!==null&&n&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${n.currentTime} due to low buffer (${q(e)})`);this.warn(r.message),t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:n,hls:r}=this,i=r?.config;if(!n||!t||!i)return 0;let a=n.currentTime,o=J.bufferInfo(n,a,0);Gf(o,a,t,r);let s=a<o.start?o.start:o.nextStart;if(s){let l=o.len<=i.maxBufferHole,u=o.len>0&&o.len<1&&n.readyState<3,d=s-a;if(d>0&&(l||u)){if(d>i.maxBufferHole){let n=!1;if(a===0){let e=t.getAppendedFrag(0,z.MAIN);e&&s<e.end&&(n=!0)}if(!n&&e){var c;if(!((c=r.loadLevelObj)!=null&&c.details)||Hf(r.inFlightFragments,s))return 0;let n=!1,i=e.end;for(;i<s;){let e=Wf(i,t),r=e?e.duration:0;if(r>0)i+=r;else{n=!0;break}}if(n)return 0}}let{nudgeMaxRetry:l,skipBufferHolePadding:u}=i,f=++this.skipRetry>l,p=Math.max(s,a)+u;if(f||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${p}`),this.moved=!0,n.currentTime=p),!(e!=null&&e.gap)||f){let t=Error(f?`Playhead still not moving after seeking over buffer hole from ${a} to ${p} after ${i.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${p}`),n={type:F.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:f,error:t,reason:t.message,buffer:o.len,bufferInfo:o};e&&(`fragment`in e?n.part=e:n.frag=e),r.trigger(L.ERROR,n)}return p}}return 0}_tryNudgeBuffer(e){let{hls:t,media:n,nudgeRetry:r}=this,i=t?.config;if(!n||!i)return 0;let a=n.currentTime;if(this.nudgeRetry++,r<i.nudgeMaxRetry){let o=a+(r+1)*i.nudgeOffset,s=Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(s.message),n.currentTime=o,t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_NUDGE_ON_STALL,error:s,fatal:!1,buffer:e.len,bufferInfo:e})}else{let n=Error(`Playhead still not moving while enough data buffered @${a} after ${i.nudgeMaxRetry} nudges`);this.error(n.message),t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,error:n,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Hf(e,t){let n=Uf(e.main);if(n&&n.start<=t)return n;let r=Uf(e.audio);return r&&r.start<=t?r:null}function Uf(e){if(!e)return null;switch(e.state){case Q.IDLE:case Q.STOPPED:case Q.ENDED:case Q.ERROR:return null}return e.frag}function Wf(e,t){return t.getAppendedFrag(e,z.MAIN)||t.getPartialFragment(e)}function Gf(e,t,n,r){let i=r.latestLevelDetails,a=Wf(t,n);if(ks(r.config)&&!e.nextStart&&i&&a&&r.interstitialsManager){let n=`type`in a?a:a.fragment,o=sa(i,n.sn);o?.level===n.level&&Os(o,r.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}var Kf=.25;function qf(){if(!(typeof self>`u`))return self.VTTCue||self.TextTrackCue}function Jf(e,t,n,r,i){let a=new e(t,n,``);try{a.value=r,i&&(a.type=i)}catch{a=new e(t,n,q(i?H({type:i},r):r))}return a}var Yf=(()=>{let e=qf();try{e&&new e(0,1/0,``)}catch{return Number.MAX_VALUE}return 1/0})(),Xf=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(L.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){let e=this.hls?.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&=(this.id3Track.remove(),null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return Mf(e,`metadata`,`id3`,``,`hidden`)}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:n,enableID3MetadataCues:r}=this.hls.config;if(!n&&!r)return;let{samples:i}=t;this.id3Track||=this.createTrack(this.media);let a=qf();if(a)for(let e=0;e<i.length;e++){let t=i[e].type;if(t===ec.emsg&&!n||!r)continue;let o=Rn(i[e].data),s=i[e].pts,c=s+i[e].duration;c>Yf&&(c=Yf),c-s<=0&&(c=s+Kf);for(let e=0;e<o.length;e++){let n=o[e];if(!zn(n)){this.updateId3CueEnds(s,t);let e=Jf(a,s,c,n,t);e&&this.id3Track.track.addCue(e)}}}}updateId3CueEnds(e,t){let n=this.id3Track?.track.cues;if(n)for(let r=n.length;r--;){let i=n[r];i.type===t&&i.startTime<e&&i.endTime===Yf&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){let{id3Track:i,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:s}}=a;if(i&&(o||s)){let e;e=r===`audio`?e=>e.type===ec.audioId3&&s:r===`video`?e=>e.type===ec.emsg&&o:e=>e.type===ec.audioId3&&s||e.type===ec.emsg&&o,Ff(i.track,t,n,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:n,timelineOffset:r,enableDateRangeMetadataCues:i,interstitialsController:a}=this.hls.config;if(!i)return;let o=qf();if(n&&r&&!a){let{fragmentStart:t,fragmentEnd:r}=e,i=this.assetCue;i?(i.startTime=t,i.endTime=r):o&&(i=this.assetCue=Jf(o,t,r,{assetPlayerId:this.hls.config.assetPlayerId},`hlsjs.interstitial.asset`),i&&(i.id=n,this.id3Track||=this.createTrack(this.media),this.id3Track.track.addCue(i),i.addEventListener(`enter`,this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:s}=this,{dateRanges:c}=e,l=Object.keys(c),u=this.dateRangeCuesAppended;if(s&&t){var d;if((d=s.track.cues)!=null&&d.length){let e=Object.keys(u).filter(e=>l.indexOf(e)===-1);for(let t=e.length;t--;){let n=e[t],r=u[n]?.cues;delete u[n],r&&Object.keys(r).forEach(e=>{let t=r[e];if(t){t.removeEventListener(`enter`,this.onEventCueEnter);try{s.track.removeCue(t)}catch{}}})}}else u=this.dateRangeCuesAppended={}}let f=e.fragments[e.fragments.length-1];if(l.length!==0&&P(f?.programDateTime)){this.id3Track||=this.createTrack(this.media);for(let e=0;e<l.length;e++){let t=l[e],n=c[t],r=n.startTime,i=u[t],s=i?.cues||{},d=i?.durationKnown||!1,f=Yf,{duration:p,endDate:m}=n;if(m&&p!==null)f=r+p,d=!0;else if(n.endOnNext&&!d){let e=l.reduce((e,t)=>{if(t!==n.id){let r=c[t];if(r.class===n.class&&r.startDate>n.startDate&&(!e||n.startDate<e.startDate))return r}return e},null);e&&(f=e.startTime,d=!0)}let h=Object.keys(n.attr);for(let e=0;e<h.length;e++){let c=h[e];if(!lo(c))continue;let l=s[c];if(l)d&&!(i!=null&&i.durationKnown)?l.endTime=f:Math.abs(l.startTime-r)>.01&&(l.startTime=r,l.endTime=f);else if(o){let e=n.attr[c];uo(c)&&(e=Un(e));let i=Jf(o,r,f,{key:c,data:e},ec.dateRange);i&&(i.id=t,this.id3Track.track.addCue(i),s[c]=i,a&&(c===`X-ASSET-LIST`||c===`X-ASSET-URL`)&&i.addEventListener(`enter`,this.onEventCueEnter))}}u[t]={cues:s,dateRange:n,durationKnown:d}}}}};function Zf(){return self.SourceBuffer||self.WebKitSourceBuffer}function Qf(){if(!an())return!1;let e=Zf();return!e||e.prototype&&typeof e.prototype.appendBuffer==`function`&&typeof e.prototype.remove==`function`}function $f(){if(!Qf())return!1;let e=an();return typeof e?.isTypeSupported==`function`&&([`avc1.42E01E,mp4a.40.2`,`av01.0.01M.08`,`vp09.00.50.08`].some(t=>e.isTypeSupported($r(t,`video`)))||[`mp4a.40.2`,`fLaC`].some(t=>e.isTypeSupported($r(t,`audio`))))}function ep(){var e;let t=Zf();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)==`function`}var tp={DISABLED:0,SWITCHING:1,SWITCHED:2},np=100,rp=class extends Ds{constructor(e,t,n){super(e,t,n,`stream-controller`,z.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=tp.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let e=this.media,t=e?e.currentTime:null;if(t===null||!P(t)||(this.log(`Media seeked to ${t}`),!this.getBufferedFrag(t)))return;let n=this.getFwdBufferInfoAtPos(e,t,z.MAIN,0);if(!n||n.len===0){this.log(`Main buffer empty at ${t} on "seeked" event: ${n&&n.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(L.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(L.BUFFER_CREATED,this.onBufferCreated,this),e.on(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(L.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(L.BUFFER_CREATED,this.onBufferCreated,this),e.off(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:n,hls:r}=this;if(this.stopLoad(),this.setInterval(np),this.level=-1,!this.startFragRequested){let e=r.startLevel;e===-1&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}n>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${n}`),e=n),this.state=Q.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Q.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Q.WAITING_LEVEL:{let{levels:e,level:t}=this,n=e?.[t],r=n?.details;if(r&&(!r.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(r))break;this.state=Q.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=Q.IDLE;break}break}case Q.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===Q.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:n,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[i]))return;let a=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;let s=this.getLevelDetails();if(s&&this._streamEnded(o,s)&&this.altAudio!==tp.SWITCHING){let e={type:this.targetBufferType()};this.hls.trigger(L.BUFFER_EOS,e),this.state=Q.ENDED;return}if(!this.buffering)return;e.loadLevel!==i&&e.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;let c=a.details;if(!c||this.state===Q.WAITING_LEVEL||this.waitForLive(a)){this.level=i,this.state=Q.WAITING_LEVEL,this.startFragRequested=!1;return}let l=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(l>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);let d=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&Tt(f)&&this.fragmentTracker.getState(f)!==Z.OK){let e=(this.backtrackFragment??f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,d)){if(!f.gap){let e=this.audioOnly&&!this.altAudio?B.AUDIO:B.VIDEO,t=(e===B.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e)}f=this.getNextFragmentLoopLoading(f,c,o,z.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||this.loadFragment(f,a,d))}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);r===Z.NOT_LOADED||r===Z.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,n):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,1/0),this.altAudio!==tp.DISABLED&&(this.getLevelDetails()?.fragmentStart||0)>this.lastCurrentTime&&super.flushMainBuffer(0,1/0,`audio`)}getBufferOutput(){return this.mediaBuffer&&this.altAudio===tp.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let t=this.fragPlaying;if(t){let n=t.level;this.hls.trigger(L.FRAG_CHANGED,{frag:t,previousFrag:e}),e?.level!==n&&this.hls.trigger(L.LEVEL_SWITCHED,{level:n})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===tp.SWITCHED&&!this.audioOnly?`video`:null}onMediaAttached(e,t){super.onMediaAttached(e,t);let n=t.media;Y(n,`playing`,this.onMediaPlaying),Y(n,`seeked`,this.onMediaSeeked)}onMediaDetaching(e,t){let{media:n}=this;n&&(X(n,`playing`,this.onMediaPlaying),X(n,`seeked`,this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log(`Trigger BUFFER_RESET`),this.hls.trigger(L.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=tp.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let n=!1,r=!1;for(let e=0;e<t.levels.length;e++){let i=t.levels[e].audioCodec;i&&(n||=i.indexOf(`mp4a.40.2`)!==-1,r||=i.indexOf(`mp4a.40.5`)!==-1)}this.audioCodecSwitch=n&&r&&!ep(),this.audioCodecSwitch&&this.log(`Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC`),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:n}=this;if(!n||this.state!==Q.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=Q.WAITING_LEVEL)}onLevelLoaded(e,t){var n;let{levels:r,startFragRequested:i}=this,a=t.level,o=t.details,s=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:``}, cc [${o.startCC}, ${o.endCC}] duration:${s}`);let c=t.levelInfo,l=this.fragCurrent;l&&(this.state===Q.FRAG_LOADING||this.state===Q.FRAG_LOADING_WAITING_RETRY)&&l.level!==t.level&&l.loader&&this.abortCurrentFrag();let u=0;if(o.live||(n=c.details)!=null&&n.live){if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,this.levelLastLoaded?.details)}if(c.details=o,this.levelLastLoaded=c,i||this.setStartPosition(o,u),this.hls.trigger(L.LEVEL_UPDATED,{details:o,level:a}),this.state===Q.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=Q.IDLE}i&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((e,t)=>{if(t>=o.startCC)return!0;delete this.initPTS[t]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:n}=this;if(!n)return;let r=this.hls.liveSyncPosition,i=this.playhead,a=e.fragmentStart,o=e.edge,s=i>=a-t.maxFragLookUpTolerance&&i<=o;if(r!==null&&n.duration>r&&(i<r||!s)){let a=t.liveMaxLatencyDuration===void 0?t.liveMaxLatencyDurationCount*e.targetduration:t.liveMaxLatencyDuration;if((!s&&n.readyState<4||i<o-a)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),n.readyState)){if(this.warn(`Playback: ${i} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r}`),this.config.liveSyncMode===`buffered`){var c;let e=J.bufferInfo(n,r,0);if(!((c=e.buffered)!=null&&c.length)){n.currentTime=r;return}if(e.start<=i){n.currentTime=r;return}let{nextStart:t}=J.bufferedInfo(e.buffered,i,0);t&&(n.currentTime=t)}else n.currentTime=r}}}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{levels:i}=this;if(!i){this.warn(`Levels were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let a=i[t.level];if(!a){this.warn(`Level ${t.level} not found on progress`);return}let o=a.details;if(!o){this.warn(`Dropping fragment ${t.sn} of level ${t.level} after level details were reset`),this.fragmentTracker.removeFragment(t);return}let s=a.videoCodec,c=o.PTSKnown||!o.live,l=t.initSegment?.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new Al(this.hls,z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=f!==-1,{decryptRange:m,byteRange:h}=qa(t,n,this.iframesOnly),g=new Qa(t.level,t.sn,t.stats.chunkCount,h?h.end-h.start:r.byteLength,f,p,t.duration,this.iframesOnly,m),_=this.initPTS[t.cc];d.push(r,l,u,s,t,n,o.totalduration,c,g,_)}onAudioTrackSwitching(e,t){let n=this.hls,r=this.altAudio!==tp.DISABLED;if(Yi(t.url,n))this.altAudio=tp.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log(`Switching on main audio, use media.buffered to schedule main fragment loading`),this.mediaBuffer=this.media;let e=this.fragCurrent;e&&(this.log(`Switching to main audio track, cancel main fragment load`),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=tp.DISABLED,this.fragmentTracker.removeAllFragments(),n.once(L.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(L.AUDIO_TRACK_SWITCHED,t)}),n.trigger(L.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null});return}n.trigger(L.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let n=Yi(t.url,this.hls);if(n){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log(`Switching on alternate audio, use video.buffered to schedule main fragment loading`),this.mediaBuffer=e)}this.altAudio=n?tp.SWITCHED:tp.DISABLED,this.tick()}onBufferCreated(e,t){let n=t.tracks,r,i,a=!1;for(let e in n){let t=n[e];if(t.id===`main`){if(i=e,r=t,e===`video`){let t=n[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:n,part:r}=t,i=n.type===z.MAIN;if(i){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Q.PARSED&&(this.state=Q.IDLE);return}let e=!1;if(Tt(n)&&(e=!!n.gap&&!n.tagList.some(e=>e[0]===`GAP`)),this.fragBufferedComplete(n,r),e){n.stats.retry++;let e=this.levels?.[n.level];e&&e.fragmentError++}}let a=this.media;a&&(!this._hasEnoughToStart&&J.getBuffered(a).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){if(t.fatal){this.state=Q.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(z.MAIN,t);break;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Q.WAITING_LEVEL&&t.context?.type===R.LEVEL&&(this.state=Q.IDLE);break;case I.BUFFER_APPEND_NO_PROGRESS:if(t.parent!==`main`)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case I.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(z.MAIN,t);break;case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case I.BUFFER_FULL_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,1/0));break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Q.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==B.AUDIO||!this.altAudio){let e=(t===B.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,n=this.startPosition;if(n>=0&&t<n){if(e.seeking){this.log(`could not seek to ${n}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&n&&(n+=r);let i=this.getLevelDetails(),a=J.getBuffered(e),o=a.length?a.start(0):0,s=o-n,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||s>0&&(s<c||this.loadingParts&&s<2*(i?.partTarget||0)))&&(this.log(`adjusting start position by ${s} to match buffer start`),n+=s,this.startPosition=n),t<n&&(this.log(`seek to target start position ${n} from current time ${t} buffer start ${o}`),e.currentTime=n)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log(`Swapping audio codec`),t=t.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{let{hls:n}=this,r=e?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=Q.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let i=r.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),n.trigger(L.FRAG_LOADED,e),r.bitrateTest=!1}).catch(t=>{this.state!==Q.STOPPED&&this.state!==Q.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:n}=this,{remuxResult:r,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a){this.resetWhenMissingContext(i);return}let{frag:o,part:s,level:c}=a,{video:l,text:u,id3:d,initSegment:f}=r,{details:p}=c,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Q.PARSING,f){let e=f.tracks;if(e){let r=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,e,r,i),n.trigger(L.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}let r=f.initPTS,a=f.timescale,s=this.initPTS[o.cc];if(P(r)&&(!s||s.baseTime!==r||s.timescale!==a)){let e=f.trackId;this.initPTS[o.cc]={baseTime:r,timescale:a,trackId:e};let i=this.initPTS.slice(0);n.trigger(L.INIT_PTS_FOUND,{timestampOffsets:i,frag:o,id:t,initPTS:r,timescale:a,trackId:e})}}if(l&&p){m&&l.type===`audiovideo`&&this.logMuxedErr(o);let e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,n=!e||o.cc>e.cc;if(r.independent!==!1){let{startPTS:e,endPTS:r,startDTS:a,endDTS:c}=l;if(s)s.elementaryStreams[l.type]={startPTS:e,endPTS:r,startDTS:a,endDTS:c};else if(l.firstKeyFrame&&l.independent&&i.id===1&&!n&&(this.couldBacktrack=!0),l.dropped&&l.independent){let i=this.getMainFwdBufferInfo(),a=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,s=l.firstKeyFramePTS?l.firstKeyFramePTS:e;if(!t&&a<s-this.config.maxBufferHole&&!n){this.backtrack(o);return}n&&(o.gap=!0),o.setElementaryStreamInfo(l.type,o.start,r,o.start,c,!0)}else t&&e-(p.appliedTimelineOffset||0)>zf&&(o.gap=!0);o.setElementaryStreamInfo(l.type,e,r,a,c),this.backtrackFragment&&=o,this.bufferFragmentData(l,o,s,i,t||n)}else if(t||n)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=m;s&&(s.elementaryStreams[B.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(B.AUDIO,e,t,n,r),this.bufferFragmentData(m,o,s,i)}if(p&&d!=null&&d.samples.length){let e={id:t,frag:o,details:p,samples:d.samples};n.trigger(L.FRAG_PARSING_METADATA,e)}if(p&&u){let e={id:t,frag:o,details:p,samples:u.samples};n.trigger(L.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${Tt(e)?`Media`:`Init`} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,n,r){if(this.state!==Q.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(n));let{audio:i,video:a,audiovideo:o}=t;if(i){let n=e.audioCodec,r=si(i.codec,n);if(r===`mp4a`&&(r=`mp4a.40.5`),this.audioCodecSwitch){r&&=r.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`;let e=i.metadata;e&&`channelCount`in e&&(e.channelCount||1)!==1&&!Gr()&&(r=`mp4a.40.5`)}r&&r.indexOf(`mp4a.40.5`)!==-1&&Jr()&&i.container!==`audio/mpeg`&&(r=`mp4a.40.2`,this.log(`Android: force audio codec to ${r}`)),n&&n!==r&&this.log(`Swapping manifest audio codec "${n}" for "${r}"`),i.levelCodec=r,i.id=z.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${r||``}/${n||``}/${i.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=z.MAIN;let n=a.codec;if(n?.length===4)switch(n){case`hvc1`:case`hev1`:a.codec=`hvc1.1.6.L120.90`;break;case`av01`:a.codec=`av01.0.04M.08`;break;case`avc1`:a.codec=`avc1.42e01e`}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||``}/${n}]${a.codec===n?``:` parsed-corrected=`+a.codec}${a.supplemental?` supplemental=`+a.supplemental:``}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(n),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let s=Object.keys(t);if(s.length){if(this.hls.trigger(L.BUFFER_CODECS,t),!this.hls)return;s.forEach(e=>{let i=t[e].initSegment;i!=null&&i.byteLength&&this.hls.trigger(L.BUFFER_APPENDING,{type:e,data:i,frag:n,part:null,chunkMeta:r,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,z.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,n=e?.[t];return n?this.getMaxBufferLength(n.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Q.IDLE}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){if(this.fragPlaying)return this.fragPlaying;let e=this.media?.currentTime||this.lastCurrentTime;return P(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){let e=this.media?.currentTime||this.lastCurrentTime;if(P(e)){let t=this.getLevelDetails(),n=this.currentFrag||(t?na(null,t.fragments,e):null);if(n){let t=n.programDateTime;if(t!==null){let r=t+(e-n.start)*1e3;return new Date(r)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},ip=class extends rp{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{let e=this.media;e!=null&&e.seeking&&(e.currentTime=e.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;let{seekOnAppend:n}=t,r=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=r,this.startPosition=e,this.state){case Q.STOPPED:case Q.ENDED:case Q.ERROR:this.state=Q.IDLE}this.state===Q.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[r,t]):this.nextOp=[r,t],this.hls.off(L.BUFFERED_TO_END,this.onBufferedToEnd);let i=this.media;n&&i&&this.seekTo(r)&&(this.currentOp=[r,t],this.nextOp=void 0,this.flushPipeline(r,!0))}seekTo(e){let t=this.media;if(t){let n=this.getLevelDetails()?.edge,r=n===void 0?t.duration:n;if(e>=r&&(e=r-.01),J.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,z.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let n=this.cached;n.push(e),this.cachedSize+=t.buffer.byteLength;let r=this.hls.config.iframeCacheLimit;for(;this.cachedSize>r&&n.length>1;){let e=n.shift();if(e.data)this.cachedSize-=e.data.byteLength,e.data=void 0;else{this.cached=n.filter(e=>!!e.data),this.cachedSize=n.reduce((e,{data:t})=>t?t.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e;this.cacheFragmentData&&!n&&r!=null&&r.byteLength&&!t.data&&Tt(t)&&this.cacheSet(t,new Uint8Array(r.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if((r===Z.NOT_LOADED||r===Z.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,n)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let n=e.decryptdata;return n?.keyFormat!==`identity`||!!n.key}replayCachedFragment(e){let t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;let n=e.stats=new Ct;n.loading.start=n.loading.first=n.loading.end=self.performance.now(),n.loaded=n.total=t.byteLength,n.chunkCount=1,this.state=Q.FRAG_LOADING;let r={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(r),this.hls.trigger(L.FRAG_LOADED,r),this._handleFragmentLoadComplete(r)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:n,nextOp:r}=this;this.currentOp=this.nextOp=void 0,this.state=Q.STOPPED,n!=null&&n[1].seekOnAppend&&(this.flushPipeline(n[0],!r),this.seekTo(n[0])||this.log(`Could not seek to ${n[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?_a(J.getBuffered(this.media)):`none`}`)),r&&this.loadMediaAt.apply(this,r)}flushPipeline(e,t){if(t){let t=this.media;if(t){let n=J.bufferInfo(t,e,0),r=n.len?n.nextStart:0;r&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,z.MAIN),this.flushMainBuffer(r,1/0))}this.hls.once(L.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(L.BUFFER_EOS,{type:`video`})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){let e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,n){let r=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,n||r||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let n=t.duration;return{len:n,start:e,end:e+n,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,z.MAIN);return!!(t!=null&&t.endList)}},ap=class extends ip{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){let t=this._img?.src;t&&self.URL.revokeObjectURL(t),this._img=e}loadMediaAt(e){if(!this.hls)return;let t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case Q.STOPPED:case Q.ENDED:case Q.ERROR:this.state=Q.IDLE}if(this.state===Q.IDLE){if(this.hls.resumeBuffering(),this.media||={},this.tick(),this.state===Q.IDLE){let t=this.getBufferedAt(e);t&&(this.fragCurrent=t,this.updateImage(t,null))}}else{let n=this.fragCurrent;(!n||e>=n.start&&e<n.end)&&(this.queued=[t])}}updateImage(e,t,n){let r=e.data;r||this.fragmentTracker.removeFragment(e);let i=this._img;if(i&&r){let a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,i.onload=()=>{if(!this.hls)return;let r=this.hls.levels[e.level];r!=null&&r.fragmentError&&(r.fragmentError=0,e.stats.retry=0);let i=self.performance.now(),a=t?t.stats:e.stats;a.buffering.end=e.stats.buffering.end=i,this.hls.trigger(L.FRAG_BUFFERED,{frag:e,part:t,stats:a,id:e.type,chunkMeta:n})},i.onerror=()=>{this.handleError(`Image decode error`,e,t,n)};let s=i.src;s&&self.URL.revokeObjectURL(s);let c=new Blob([r],{type:`image/jpeg`});i.src=self.URL.createObjectURL(c)}else this.state=Q.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,n,r){if(!this.hls)return;let i=Error(e);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,chunkMeta:r,frag:t,part:n,fatal:!1,error:i,err:i})}_bufferInitSegment(){}bufferFragmentData(e,t,n,r){super.bufferFragmentData(e,t,n,r,!0);let i=K(new Uint8Array(e.data1),[`mdat`]);if(i.length===0){this.handleError(`Could not find I-Frame mdat`,t,n,r);return}let a=t;this.cacheSet(a,i[0]),this.updateImage(a,n,r)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){let e=this.fragPrevious?.start;if(e!==void 0){let t=this.getAppendedFrag(e);if(t&&!Et(t,this.fragPlaying))return this.fragPlaying=t,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},op=10,sp=`Image I-Frame player does not accept HTMLMediaElements`,cp={seekOnAppend:!0},lp,up,dp=class extends Xt{constructor(e,t){super(`iframes`,e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,lp||=fp(t),up||=pp(lp),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(L.MANIFEST_LOADING,this.clearAsset,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this),e.on(L.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(L.MANIFEST_LOADING,this.clearAsset,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this),e.off(L.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){let n=this.hls?.pathwayPriority;t.length&&n&&this.iframeInstances.forEach(e=>{e.pathwayPriority=n})}onInitPtsFound(e,{id:t,timestampOffsets:n}){t===z.MAIN&&(this.initPTS=n)}onFragBuffered(e,t){let n=this.hls;n&&n.hasEnoughToStart&&(n.mainForwardBufferInfo?.len||0)>op&&this.iframeInstances.forEach(e=>{if(!e.loadingEnabled){var t;e.startLoad(((t=this.hls)==null||(t=t.media)==null?void 0:t.currentTime)||0)}})}createIFramePlayer(e){return this.createInstance(lp,this.hls?.iframeVariants,e)}createImageIFramePlayer(e){let t=this.hls?.iframeVariants.filter(e=>e.imageCodec);return this.createInstance(up,t,e,`image-`)}createInstance(e,t,n,r){let{hls:i}=this;if(!i)return null;let{url:a,userConfig:o,latestLevelDetails:s,loadLevelObj:c,loadLevel:l,bandwidthEstimate:u,sessionId:d}=i,{stats:f,variableList:p}=this;if(!(t!=null&&t.length)||!f||!a)return null;let m=`${r||``}iframe-player-${this.instanceCounter++}`,h=i.levels,g=c||h[l],_=Zi(g,o.videoPreference),v=g?.pathwayId||`.`,y=new e(H(H({},o),{},{loggerId:m,primarySessionId:d,videoPreference:_,abrEwmaDefaultEstimate:u,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},n),a,this.initPTS,s);return this.iframeInstances=this.iframeInstances.filter(e=>!e.url),this.iframeInstances.push(y),y.trigger(L.MANIFEST_LOADED,{levels:t,contentSteering:{uri:``,pathwayId:v},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:p}),y}};function fp(e){return class extends e{constructor(e,t,n,r){e.streamController||=ip,super(e),this._url=t,this.streamController.setInitPts(n),this.streamController.initDetails=r}loadSource(){}loadMediaAt(e,t=cp){if(e<0)return;let n=H(H({},cp),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,n)}}}function pp(e){return class extends e{constructor(e,t,n,r){e.cmcdController=void 0,e.emeController=void 0,e.streamController||=ap,e.capLevelController=void 0,e.bufferController=void 0,super(e,t,n,r)}attachImage(e){this.streamController.image=e}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw Error(sp)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}}var mp=.025,hp=function(e){return e[e.Point=0]=`Point`,e[e.Range=1]=`Range`,e}({});function gp(e,t,n){return`${e.identifier}-${n+1}-${df(t)}`}var _p=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat(`X-RESUME-OFFSET`,this.resumeOffset),this.playoutLimit=e.attr.optionalFloat(`X-PLAYOUT-LIMIT`,this.playoutLimit),this.restrictions=e.attr.enumeratedStringList(`X-RESTRICT`,this.restrictions),this.snapOptions=e.attr.enumeratedStringList(`X-SNAP`,this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>0&&e>=this.assetList.length)return!0;let t=this.playoutLimit;return e<=0||isNaN(t)?!1:t===0||(this.assetList[e]?.startOffset||0)>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return yp(t,e)?vp(e,t):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime;return t-vp(t,e)<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=P(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return yp(t,e)?vp(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:!this.appendInPlaceDisabled&&!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<mp))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart===null?this.startTime:this._timelineStart}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return t=this._duration===null?this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0:this._duration,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr[`X-TIMELINE-OCCUPIES`]===`RANGE`?hp.Range:hp.Point}get supplementsPrimary(){return this.dateRange.attr[`X-TIMELINE-STYLE`]===`PRIMARY`}get contentMayVary(){return this.dateRange.attr[`X-CONTENT-MAY-VARY`]!==`NO`}get assetUrl(){return this.dateRange.attr[`X-ASSET-URI`]}get assetListUrl(){return this.dateRange.attr[`X-ASSET-LIST`]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Sp(this)}};function vp(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<mp)?t.start:t.start+t.duration}function yp(e,t){return t>e.start-mp&&t<e.start+e.duration+mp}function bp(e,t,n){let r=new self.URL(e,n);return r.protocol!==`data:`&&wi(r,`_HLS_primary_id`,t),r}function xp(e,t){for(;(n=e.assetList[++t])!=null&&n.error;)var n;return t}function Sp(e){return`["${e.identifier}" ${e.cue.pre?`<pre>`:e.cue.post?`<post>`:``}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function Cp(e){let t=e.timelineStart,n=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}var wp=class{constructor(e,t,n,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(L.PLAYOUT_LIMIT_REACHED,{})};let i=this.hls=new e(t);this.interstitial=n,this.assetItem=r;let a=()=>{this.hasDetails=!0};i.once(L.LEVEL_LOADED,a),i.once(L.AUDIO_TRACK_LOADED,a),i.once(L.SUBTITLE_TRACK_LOADED,a),i.on(L.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener(`timeupdate`,this.checkPlayout),this.appendInPlace&&i.on(L.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,i.trigger(L.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e){if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=bp(t,e.config.primarySessionId||``).href}catch{}e.loadSource(t)}}}bufferedInPlaceToEnd(e,t){var n;if(!this.appendInPlace)return!1;if((n=this.hls)!=null&&n.bufferedToEnd)return!0;if(!e)return!1;let r=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset+(t||0),a=J.bufferInfo(e,i,.02);return this.getAssetTime(a.end)>=r-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){return this.hls?.media||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=J.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let n=t-this.startOffset;if(n>0&&n<e)return n}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){return this.hls?.config.timelineOffset||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let n=e-t;if(Math.abs(n)>1/9e4&&this.hls){if(this.hasDetails)throw Error(`Cannot set timelineOffset after playlists are loaded`);this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-t),n)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener(`timeupdate`,this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls?.transferMedia()||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,n){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,n){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,n){var r;(r=this.hls)==null||r.off(e,t)}toString(){return`HlsAssetPlayer: ${Cp(this.assetItem)} ${this.hls?.sessionId} ${this.appendInPlace?`append-in-place`:``}`}},Tp=.033,Ep=class extends Xt{constructor(e,t){super(`interstitials-sched`,t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((n,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,n+1):n,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let n=-1;e.nextEvent?n=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(n=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[n]||(t===void 0&&(t=e.start),n=this.findItemIndexAtTime(t));n>=0&&(i=r[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(e,t){let n=this.items;if(n)for(let r=0;r<n.length;r++){let i=n[r];t&&t!==`primary`&&(i=i[t]);let a=i.start,o=n[r].event,s=o!=null&&o.cue.pre?o.duration:i.end;if(e===a||e>a&&e<s)return r}return-1}findJumpRestrictedIndex(e,t){let n=this.items;if(n)for(let r=e;r<=t&&n[r];r++){let e=n[r].event;if(e!=null&&e.restrictions.jump&&!e.appendInPlace)return r}return-1}findEventIndex(e){let t=this.items;if(t){for(let n=t.length;n--;)if(t[n].event?.identifier===e)return n}return-1}findAssetIndex(e,t){let n=e.assetList,r=n.length;if(r>1)for(let e=0;e<r;e++){let i=n[e];if(!i.error){let n=i.timelineStart;if(t===n||t>n&&(t<n+(i.duration||0)||e===r-1))return e}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let e=t.assetList,n=e[e.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t,n=0){let r=e.main.details,{dateRanges:i}=r,a=this.events,o=this.parseDateRanges(i,{url:r.url},t),s=Object.keys(i),c=a?a.filter(e=>s.indexOf(e.identifier)===-1):[];o.length&&o.sort((e,t)=>{let n=e.cue.pre,r=e.cue.post,i=t.cue.pre,a=t.cue.post;if(n&&!i)return-1;if(i&&!n||r&&!a)return 1;if(a&&!r)return-1;if(!n&&!i&&!r&&!a){let n=e.startTime,r=t.startTime;if(n!==r)return n-r}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=o,c.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,c,n)}updateSchedule(e,t=[],n=0,r=!1){let i=this.events||[];if(i.length||t.length||this.length<2){let a=this.items,o=this.parseSchedule(i,e,n);(r||t.length||a?.length!==o.length||o.some((e,t)=>Math.abs(e.playout.start-a[t].playout.start)>.005||Math.abs(e.playout.end-a[t].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,n){let r=[],i=Object.keys(e);for(let a=0;a<i.length;a++){let o=i[a],s=e[o];if(s.isInterstitial){let e=this.eventMap[o];e?e.setDateRange(s):(e=new _p(s,t),this.eventMap[o]=e,n===!1&&(e.appendInPlace=n)),r.push(e)}}return r}parseSchedule(e,t,n=0){let r=[],i=t.main.details,a=i.live?1/0:i.edge,o=0;if(e=e.filter(e=>!e.error&&!(e.cue.once&&e.hasPlayed)),e.length){this.resolveOffsets(e,t);let s=0,c=0;if(e.forEach((t,l)=>{let u=t.cue.pre,d=t.cue.post,f=e[l-1]||null,p=t.appendInPlace,m=d?a:t.startOffset,h=t.duration,g=t.timelineOccupancy===hp.Range?h:0,_=u&&i.live?n+(t.resumeOffset||0):0,v=_||t.resumptionOffset,y=f?.startTime===m,b=m+t.cumulativeDuration,x=p?b+h:m+v;if(u||!d&&m<=0){let e=c;c+=g,t.timelineStart=b;let n=o;o+=h,r.push({event:t,start:b,end:x,playout:{start:n,end:o},integrated:{start:e,end:c}})}else if(m<=a){if(!y){let n=m-s;if(n>Tp){let i=s,a=c;c+=n;let u=o;o+=n;let d={previousEvent:e[l-1]||null,nextEvent:t,start:i,end:i+n,playout:{start:u,end:o},integrated:{start:a,end:c}};r.push(d)}else n>0&&f&&(f.cumulativeDuration+=n,r[r.length-1].end=m)}d&&(x=b),t.timelineStart=b;let n=c;c+=g;let i=o;o+=h,r.push({event:t,start:b,end:x,playout:{start:i,end:o},integrated:{start:n,end:c}})}else return;let S=_||t.resumeTime;s=d||S>a?a:!u&&x&&t.appendInPlaceStarted&&S-x>Tp?x:S}),s<a){let e=s,t=c,n=a-s;c+=n;let i=o;o+=n,r.push({previousEvent:r[r.length-1]?.event||null,nextEvent:null,start:s,end:e+n,playout:{start:i,end:o},integrated:{start:t,end:c}})}this.setDurations(a,o,c)}else r.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return r}setDurations(e,t,n){this.durations={primary:e,playout:t,integrated:n}}resolveOffsets(e,t){let n=t.main.details,r=n.live?1/0:n.edge,i=0,a=-1;e.forEach((o,s)=>{let c=o.cue.pre,l=o.cue.post,u=c?0:l?r:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=i:(i=0,a=u),!l&&o.snapOptions.in&&(o.resumeAnchor=na(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&s+1<e.length&&e[s+1].startTime-e[s].resumeTime<Tp&&(e[s+1].appendInPlace=!1,e[s+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let d=P(o.resumeOffset)?o.resumeOffset:o.duration;i+=d})}primaryCanResumeInPlaceAt(e,t){let n=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(n-r)>mp?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(r=>{let i=t[r].details,a=i.edge;if(n>=a)return this.log(`"${e.identifier}" resumption ${n} past ${r} playlist end ${a}`),!1;let o=na(null,i.fragments,n);if(!o)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${r} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;let s=r===`audio`?.175:0;return Math.abs(o.start-n)<mp+s||Math.abs(o.end-n)<mp+s?!1:(this.log(`"${e.identifier}" resumption ${n} not aligned with ${r} fragment bounds (${o.start}-${o.end} sn: ${o.sn} cc: ${o.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,n=0,r=!1,i=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],s=t+n;o.startOffset=n,o.timelineStart=s,r||=o.duration===null,i||=!!o.error;let c=o.error?0:o.duration||0;n+=c}e.duration=r&&!i?Math.max(n,e.duration):n}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Dp(e){return`[${e.event?`"`+e.event.identifier+`"`:`primary`}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}var Op=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let n=e.assetListUrl,r;try{r=bp(n,this.hls.sessionId,e.baseUrl)}catch(t){let r=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,t,n);this.hls.trigger(L.ERROR,r);return}t&&r.protocol!==`data:`&&wi(r,`_HLS_start_offset`,``+t);let i=this.hls.config,a=i.loader,o=new a(i),s={type:R.INTERSTITIAL_ASSET_LIST,responseType:`json`,url:r.href},c=i.interstitialAssetListLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return o.load(s,l,{onSuccess:(t,n,r,i)=>{let a=t.data,o=a?.ASSETS;if(!Array.isArray(o)){let t=this.assignAssetListError(e,I.ASSET_LIST_PARSING_ERROR,Error(`Invalid interstitial asset list`),r.url,n,i);this.hls.trigger(L.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(L.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:i})},onError:(t,n,r,i)=>{let a=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${n.url})`),n.url,i,r);this.hls.trigger(L.ERROR,a)},onTimeout:(t,n,r)=>{let i=this.assignAssetListError(e,I.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${n.url})`),n.url,t,r);this.hls.trigger(L.ERROR,i)}}),this.hls.trigger(L.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,n,r,i,a){return e.error=n,{type:F.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:n,networkDetails:a,stats:i}}};function kp(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function Ap(e,t){return`[${e}] Advancing timeline position to ${t}`}var jp=class extends Xt{constructor(e,t){super(`interstitials`,e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled||!this.schedule)return;let t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;let n=t<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=e,this.bufferedPos=e;let r=this.playingItem;if(!r){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0),this.checkBuffer(),n&&e<r.start||e>=r.end){var i;let t=this.findItemIndex(r),a=this.schedule.findItemIndexAtTime(e);if(a===-1&&(a=t+(n?-1:1),this.log(`seeked ${n?`back `:``}to position not covered by schedule ${e} (resolving from ${t} to ${a})`)),!this.isInterstitial(r)&&(i=this.media)!=null&&i.paused&&(this.shouldPlay=!1),!n&&a>t){let e=this.schedule.findJumpRestrictedIndex(t+1,a);if(e>t){this.setSchedulePosition(e);return}}this.setSchedulePosition(a);return}let a=this.playingAsset;if(!a){if(this.playingLastItem&&this.isInterstitial(r)){let t=r.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}let o=a.timelineStart,s=a.duration||0;if(n&&e<o||e>=o+s){var c;(c=r.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(r.event,r),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,a)}},this.onTimeupdate=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),e>this.timelinePos)this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();else return;let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let n=this.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&this.setScheduleToAssetAtTime(e,n)},this.onScheduleUpdate=(e,t)=>{let n=this.schedule;if(!n)return;let r=this.playingItem,i=n.events||[],a=n.items||[],o=n.durations,s=e.map(e=>e.identifier),c=!!(i.length||s.length);(c||t)&&this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i}
|
|
45
45
|
Schedule: ${a.map(e=>Dp(e))} pos: ${this.timelinePos}`),s.length&&this.log(`Removed events ${s}`);let l=null,u=null;r&&(l=this.updateItem(r,this.timelinePos),this.itemsMatch(r,l)?this.playingItem=l:this.waitingItem=null);let d=this.waitingItem;d&&(this.waitingItem=this.updateItem(d),!this.waitingItem&&!r&&(this.log(`INTERSTITIAL_ENDED unresolved ${Dp(d)}`),this.hls.trigger(L.INTERSTITIAL_ENDED,{event:d.event,schedule:a.slice(0),scheduleIndex:-1})));let f=this.bufferingItem;if(f&&(u=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,u)?this.bufferingItem=u:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,n=e.timelineOffset-t;if(n)try{e.timelineOffset=t}catch(r){Math.abs(n)>mp&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),c||t){if(this.hls.trigger(L.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:a.slice(0),durations:o,removedIds:s}),this.isInterstitial(r)&&s.indexOf(r.event.identifier)>-1){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}r&&this.trimInPlace(l,r),f&&u!==l&&this.trimInPlace(u,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Op(e),this.schedule=new Ep(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(L.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(L.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(L.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(L.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this),e.on(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(L.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(L.MEDIA_ENDED,this.onMediaEnded,this),e.on(L.ERROR,this.onError,this),e.on(L.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(L.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(L.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(L.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(L.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(L.BUFFER_CODECS,this.onBufferCodecs,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this),e.off(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(L.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(L.MEDIA_ENDED,this.onMediaEnded,this),e.off(L.ERROR,this.onError,this),e.off(L.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){X(e,`play`,this.onPlay),X(e,`pause`,this.onPause),X(e,`seeking`,this.onSeeking),X(e,`timeupdate`,this.onTimeupdate)}onMediaAttaching(e,t){let n=this.media=t.media;Y(n,`seeking`,this.onSeeking),Y(n,`timeupdate`,this.onTimeupdate),Y(n,`play`,this.onPlay),Y(n,`pause`,this.onPause)}onMediaAttached(e,t){let n=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!r){this.clearScheduleState();let e=this.findItemIndex(n);this.setSchedulePosition(e)}}clearScheduleState(){this.log(`clear schedule state`),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let n=!!t.transferMedia,r=this.media;if(this.media=null,!n&&(r&&this.removeMediaListeners(r),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,n=t=>t&&e.getAssetPlayer(t.identifier),r=(t,r,i,o,s)=>{if(t){let c=t[r].start,l=t.event;if(l){if(r===`playout`||l.timelineOccupancy!==hp.Point){let e=n(i);e?.interstitial===l&&(c+=e.assetItem.startOffset+e[s])}}else{let n=o===`bufferedPos`?a():e[o];c+=n-t.start}return c}return 0},i=(t,n)=>{var r;if(t!==0&&n!==`primary`&&(r=e.schedule)!=null&&r.length){let r=e.schedule.findItemIndexAtTime(t),i=e.schedule.items?.[r];if(i)return t+(i[n].start-i.start)}return t},a=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?o(`primary`):Math.max(t,0)},o=t=>{var n;return(n=e.primaryDetails)!=null&&n.live?e.primaryDetails.edge:e.schedule?.durations[t]||0},s=(t,i)=>{var a;let o=e.effectivePlayingItem;if(o!=null&&(a=o.event)!=null&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${i}"`);let s=e.effectivePlayingItem,c=e.schedule.findItemIndexAtTime(t,i),l=e.schedule.items?.[c],u=e.getBufferingPlayer(),d=u?.interstitial?.appendInPlace,f=s&&e.itemsMatch(s,l);if(s&&(d||f)){let a=n(e.playingAsset),o=a?.media||e.primaryMedia;if(o){let n=i===`primary`?o.currentTime:r(s,i,e.playingAsset,`timelinePos`,`currentTime`),c=t-n,l=(d?n:o.currentTime)+c;if(l>=0&&(!a||d||l<=a.duration)){o.currentTime=l;return}}}if(l){let n=t;if(i!==`primary`){let e=t-l[i].start;n=l.start+e}let r=!e.isInterstitial(l);if((!e.isInterstitial(s)||s.event.appendInPlace)&&(r||l.event.appendInPlace)){let t=e.media||(d?u?.media:null);t&&(t.currentTime=n)}else if(s){let a=e.findItemIndex(s);if(c>a){let t=e.schedule.findJumpRestrictedIndex(a+1,c);if(t>a){e.setSchedulePosition(t);return}}let o=0;if(r)e.timelinePos=n,e.checkBuffer();else{let e=l.event.assetList,n=t-(l[i]||l).start;for(let t=e.length;t--;){let r=e[t];if(r.duration&&n>=r.startOffset&&n<r.startOffset+r.duration){o=t;break}}}e.setSchedulePosition(c,o)}}},c=()=>{let n=e.effectivePlayingItem;if(e.isInterstitial(n))return n;let r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){let n=t(),i=e.bufferingItem;return i&&i===n&&(r(i,`playout`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)-i.playout.start||e.bufferingAsset?.startOffset)||0},get currentTime(){let t=c(),n=e.effectivePlayingItem;return n&&n===t?r(n,`playout`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)-n.playout.start:0},set currentTime(t){let n=c(),r=e.effectivePlayingItem;r&&r===n&&s(t+r.playout.start,`playout`)},get duration(){let e=c();return e?e.playout.end-e.playout.start:0},get assetPlayers(){let t=c()?.event.assetList;return t?t.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){let t=c()?.event;return t&&e.effectivePlayingAsset?t.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var t;return((t=e.schedule)==null||(t=t.events)==null?void 0:t.slice(0))||[]},get schedule(){var t;return((t=e.schedule)==null||(t=t.items)==null?void 0:t.slice(0))||[]},get interstitialPlayer(){return c()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let n=t();return e.findItemIndex(n)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return a()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,`primary`)},get duration(){return o(`primary`)},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return r(t(),`integrated`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)},get currentTime(){return r(e.effectivePlayingItem,`integrated`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)},set currentTime(e){s(e,`integrated`)},get duration(){return o(`integrated`)},get seekableStart(){return i(e.seekableStart,`integrated`)}},skip:()=>{let t=e.effectivePlayingItem,n=t?.event;if(n&&!n.restrictions.skip){let r=e.findItemIndex(t);if(n.appendInPlace){let e=t.playout.start+t.event.duration;s(e+.001,`playout`)}else e.advanceAfterAssetEnded(n,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){let e=this.playingItem,t=this.schedule?.items;return!this.playbackStarted||!e||!t?!1:this.findItemIndex(e)===t.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e;if(this.mediaSelection===null)return;let t=this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&!t.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);let r=n?.currentTime;if(r!==void 0&&P(r))return r}get primaryMedia(){return this.media||this.detachedData?.media||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let n=this.getAssetPlayer(e);n&&this.transferMediaFromPlayer(n,t)}transferMediaFromPlayer(e,t){let n=e.interstitial.appendInPlace,r=e.media;if(n&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${q(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||=!r.paused)}transferMediaTo(e,t){if(e.media===t)return;let n=null,r=this.hls,i=e!==r,a=i&&e.interstitial.appendInPlace,o=this.detachedData?.mediaSource,s;if(r.media)a&&(n=r.transferMedia(),this.detachedData=n),s=`Primary`;else{let e=this.getBufferingPlayer();e?(n=e.transferMedia(),this.detachedData=n,s=`${e}`):s=o?`detached MediaSource`:`detached media`}if(!n){if(o)n=this.detachedData,this.log(`using detachedData: MediaSource ${q(n)}`);else if(!this.detachedData||r.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(i&&e.interstitial.appendInPlace!==a){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&`mediaSource`in n&&n.mediaSource?.readyState!==`closed`;if(this.log(`${c?`transfering MediaSource`:`attaching media`} to ${i?e:`Primary`} from ${s} (media.currentTime: ${t.currentTime})`),!c&&!i){e.attachMedia(t);return}let l=c&&n?H({},n):{media:t},u=this.schedule;if(u&&i){let t=e.assetId===u.assetIdAtEnd;l.overrides={duration:u.duration,endOfStream:t||e.appendInPlace===!1}}if(!c&&a){let t=e,n=t.assetItem.timelineStart;if(n){let e=t.hls,r=Math.max(this.timelinePos-n,2**-52);e.startPosition!==r&&(this.log(`Set ${t} startPosition: ${r}`),e.config.startPosition=r,e.loadingEnabled&&e.startLoad(r))}}e.attachMedia(l)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events,n=this.hls;if(!t||this.playbackDisabled||!this.media||!n)return;this.bufferedPos===-1&&(this.bufferedPos=0);let r=this.timelinePos,i=this.effectivePlayingItem;if(r===-1){if(!n.loadingEnabled){this.log(`waiting for startLoad( <startPosition> )`);return}let r=n.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Ap(`checkStart (preroll)`,r));let n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){this.log(Ap(`checkStart`,r));let t=this.timelinePos=r>0?r:0,n=e.findItemIndexAtTime(t);this.setSchedulePosition(n)}else n.liveSyncPosition===0?this.setSchedulePosition(0):this.log(`[checkStart] waiting for live start`)}else if(i&&!this.playingItem){this.log(Ap(`checkStart (playing item)`,i.start));let t=e.findItemIndex(i);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let n=e.event,r=xp(n,n.findAssetIndex(t));if(!n.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){let t=this.getNextItemIndex(e,!0),n=this.schedule.items?.[t];n&&this.bufferedToItem(n)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!P(e.resumeOffset)&&this.hls){let e=this.getLiveStartPos();if(t){let t=this.getBufferingPlayer();return e+(t!=null&&t.interstitial.cue.pre?t.remaining:0)}return e}}getNextItemIndex(e,t){if(this.schedule){let n=this.livePrerollResumption(e.event,t);if(n!==void 0)return this.log(`find next item index @${n}`),this.schedule.findItemIndexAtTime(n)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,n){let r=xp(e,n);if(!e.isAssetPastPlayoutLimit(r)){if(e.appendInPlace){let t=e.assetList[r];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,r)}else if(this.schedule){let n=this.schedule.items;if(n){let r=n[t],i=r.event?this.getNextItemIndex(r):t+1;if(i>=n.length){this.setSchedulePosition(-1);return}let a=e.resumeTime;this.timelinePos<a&&(this.log(Ap(`advanceAfterAssetEnded`,a)),this.timelinePos=a,e.appendInPlace&&!n[i].event&&this.hls.startLoad(a+.01),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(i)}}}setScheduleToAssetAtTime(e,t){let n=this.schedule;if(!n)return;let r=t.parentIdentifier,i=n.getEvent(r);if(i){let t=n.findEventIndex(r),a=n.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,t,a-1)}}setSchedulePosition(e,t){let n=this.schedule?.items;if(!n||this.playbackDisabled)return;let r=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Dp(r)}) pos: ${this.timelinePos}`);let i=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(i)){let s=i.event,c=this.playingAsset,l=c?.identifier,u=l?this.getAssetPlayer(l):null;if(u&&l&&(!this.eventItemsMatch(i,r)||t!==void 0&&l!==s.assetList[t].identifier)){var o;let t=s.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${Cp(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(L.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:t,event:s,schedule:n.slice(0),scheduleIndex:e,player:u}),i!==this.playingItem){this.itemsMatch(i,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(l,r),u.media&&!((o=this.detachedData)!=null&&o.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(i,r)&&(this.endedItem=i,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${Dp(i)}`),s.hasPlayed=!0,this.hls.trigger(L.INTERSTITIAL_ENDED,{event:s,schedule:n.slice(0),scheduleIndex:e}),s.cue.once&&this.hls)){this.updateSchedule();let e=this.schedule?.items;if(r&&e){let o=this.findItemIndex(r),c=this.livePrerollResumption(s);if(c!==void 0){let t=c,r=this.getNextItemIndex(i);if(!this.isInterstitial(n[r])){let e=this.primaryDetails?.fragments;if(s.snapOptions.in&&e){let i=na(null,e,c);i&&(t=Math.min(Math.max(n[r].start,vp(t,i)),n[r].end))}}if(this.log(Ap(`live join (preroll)`,t)),this.timelinePos=t,r!==o&&(r||r===0)){this.advanceSchedule(r,e,void 0,i,a);return}}this.advanceSchedule(o,e,t,i,a)}return}}this.advanceSchedule(e,n,t,i,a)}advanceSchedule(e,t,n,r,i){let a=this.schedule;if(!a)return;let o=t[e]||null,s=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(t=>{let n=t.interstitial,r=a.findEventIndex(n.identifier);(r<e||r>e+1)&&this.clearInterstitial(n,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let i=o.event;if(n===void 0){n=i.cue.pre?0:a.findAssetIndex(i,this.timelinePos);let t=xp(i,n-1);if(i.isAssetPastPlayoutLimit(t)||i.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(i,e,n);return}n=t}let c=this.waitingItem;this.assetsBuffered(o,s)||this.setBufferingItem(o);let l=this.preloadAssets(i,n);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Dp(o)} ${i.appendInPlace?`append in place`:``}`),i.hasPlayed=!1,this.hls.trigger(L.INTERSTITIAL_STARTED,{event:i,schedule:t.slice(0),scheduleIndex:e})),!i.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${i}`);return}if(i.assetListLoader&&=(i.assetListLoader.destroy(),void 0),!s){this.log(`Waiting for attachMedia to start Interstitial ${i}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let u=i.assetList[n];if(!u){this.advanceAfterAssetEnded(i,e,n||0);return}if(l||=this.getAssetPlayer(u.identifier),l===null||l.destroyed){let e=i.assetList.length;this.warn(`asset ${n+1}/${e} player destroyed ${i}`),l=this.createAssetPlayer(i,u,n),l.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&i.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(l,n,t,e,s),this.shouldPlay&&kp(l.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&kp(this.hls.media)):i&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){return this.mediaSelection?.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,n){var r;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Dp(e)}`);let i=this.timelinePos;if((r=this.detachedData)!=null&&r.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(i):((i<e.start||i>=e.end||i<this.seekableStart)&&(i=this.getPrimaryResumption(e,t),this.log(Ap(`resumePrimary`,i)),this.timelinePos=i),this.attachPrimary(i,e)),!n)return;let a=this.schedule?.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Dp(e)}`),this.hls.trigger(L.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){return this.primaryLive&&this.primaryDetails?.fragmentStart||0}getPrimaryResumption(e,t,n){let r=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;let e=this.endedItem||this.playingItem,i=e!=null&&e.event?this.livePrerollResumption(e.event,n):void 0;if(i!==void 0)return i;let a=this.primaryDetails;if(a){let{fragmentStart:e,edge:t}=a;if(r<e||r>t&&!n){let n=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${r} [${e}-${t}]) snapping to liveSync ${n}`),n||e}}}return this.log(`primary resumption itemStart: ${r}`),r}getLiveStartPos(){let e=this.hls.startPosition,t=this.hls.liveSyncPosition||0,n=(this.primaryDetails?.targetduration||10)*3;return e===-1||t&&t-e<n?t||0:e}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:J.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,n){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,r),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log(Ap(`attachPrimary`,e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,t){let n=this.hls,{loadingEnabled:r,bufferingEnabled:i,startPosition:a}=n,o=n.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${r} bufferingEnabled: ${i}`),!t&&o||!r||Math.abs(a-e)>.1){let r=this.primaryDetails;if(r!=null&&r.live&&e+.5>=r.edge){let t=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${t?Dp(t):null}`),n.pauseBuffering(),this.bufferPastEdge=!0;return}n.startLoad(e,t)}else i||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(L.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(L.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let n=this.hls.levels[t.level];if(!n.details)return;let r=H(H({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=r;let i=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace,i===-1?0:i),this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){let e=this.primaryDetails,t=this.bufferedPos;if(e!=null&&e.live&&t+.5<e.edge){this.bufferPastEdge=!1;let n=this.bufferingItem;if(this.log(`Live edge ${e.edge} passed buffer: ${t} buffering item: ${n?Dp(n):null}`),n?.end===1/0){let e=this.playingItem,r=this.isInterstitial(e)&&e.event.appendInPlace;this.hls.startLoad(Math.max(t,n.start),r)}else{let e=this.getBufferingPlayer();e&&e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)&&e.hls&&e.hls.trigger(L.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let n=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=H(H({},this.altSelection),{},{audio:n});return}let i=H(H({},r),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){let n=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=H(H({},this.altSelection),{},{subtitles:n});return}let i=H(H({},r),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(e,t){let n=Vi(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(n)))}onSubtitleTrackSwitch(e,t){let n=Vi(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||t.id!==-1&&e.setSubtitleOption(n)))}onBufferCodecs(e,t){let n=t.tracks;n&&(this.requiredTracks=n)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){let e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){let n=t[e];if(n.cue.post){let e=this.getEventItem(n.identifier);e&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){let n=this.schedule?.items;return e&&n&&n[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(t.identifier,null)});let n=e.end+.25,r=J.bufferInfo(this.primaryMedia,n,0);(r.end>n||(r.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${Dp(e)} (was ${Dp(t)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){return!!t&&(e===t||e.event.identifier===t.event?.identifier)}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){let t=this.schedule.items?.[this.findEventIndex(e)];if(this.isInterstitial(t)&&t.event.identifier===e)return t}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let n=this.mediaSelection;if(!n)return;let r=this.hls?.liveSyncPosition||0;(t=this.schedule)==null||t.updateSchedule(n,[],r,e)}checkBuffer(e){let t=this.schedule?.items;if(!t)return;let n=J.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||=n.len<1,this.updateBufferedPos(n.end,t,e)}updateBufferedPos(e,t,n){let r=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],i)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),s=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;let n=this.findItemIndex(i),r=Math.min(n+1,t.length-1),a=t[r];if((s===-1&&i&&e>=i.end||(c=a.event)!=null&&c.appendInPlace&&e+.01>=a.start)&&(s=r),this.isInterstitial(i)){let e=i.event;if(r-o>1&&e.appendInPlace===!1||e.assetList.length===0&&e.assetListLoader)return}if(this.bufferedPos=e,s>n&&s>o)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(a)&&this.preloadAssets(a.event,0)}}else n&&a&&!this.itemsMatch(a,i)&&(s===o?this.bufferedToItem(a):s===o+1&&this.bufferedToItem(t[s]))}assetsBuffered(e,t){return e.event.assetList.length!==0&&!e.event.assetList.some(e=>{let n=this.getAssetPlayer(e.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,t)&&n){let{items:r,events:i}=n;if(!r||!i)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let s=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Dp(e)}`+(t?` (${s.toFixed(2)} remaining)`:``)),!this.playbackDisabled){if(a){let t=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,n)=>{let r=this.getAssetPlayer(e.identifier);r&&(n===t&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering())}this.hls.trigger(L.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let n=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(n!==null){this.bufferingAsset=null;let t=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(t,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),r=this.detachedData;if(r)r.mediaSource?this.attachPrimary(n,e,!0):this.startLoadingPrimaryAt(n);else{let e=this.playingItem,t=this.isInterstitial(e)&&e.event.appendInPlace;this.startLoadingPrimaryAt(n,t)}}}}bufferedToEvent(e,t){let n=e.event,r=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(r||!i){let e=this.preloadAssets(n,t);if(e!=null&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let n=e.assetUrl,r=e.assetList.length,i=r===0&&!e.assetListLoader,a=e.cue.once;if(i){let i=e.timelineStart,a=this.playingItem,s=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(a)&&(a==null||(o=a.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(i+.25)}let c,l=0;if((!s||s.interstitial.cue.pre)&&this.primaryLive&&(l=this.getLiveStartPos(),s&&(l+=s.remaining)),l&&!(e.cue.pre||e.cue.post)){let e=l-i;e>0&&(c=Math.round(e*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${n?1:r} ${e}${l?` live-start: ${l} start-offset: ${c} (timeline-start: ${i})`:``}`),n)return this.createAsset(e,0,0,i,e.duration,n);let u=this.assetListLoader.loadAssetList(e,c);u&&(e.assetListLoader=u)}else if(!a&&r){for(let n=t;n<r;n++){let t=e.assetList[n],r=this.getAssetPlayerQueueIndex(t.identifier);(r===-1||this.playerQueue[r].destroyed)&&!t.error&&this.createAssetPlayer(e,t,n)}let n=e.assetList[t];if(n){let e=this.getAssetPlayer(n.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let n=this.primaryDetails;n&&e>=n.edge||(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(L.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let n=0;n<t.length;n++)if(e===t[n].assetId)return n;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let n=0;n<e.length;n++)if(e[n].media===t)return e[n]}return null}createAsset(e,t,n,r,i,a){let o={parentIdentifier:e.identifier,identifier:gp(e,a,t),duration:i,startOffset:n,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,n){let r=this.hls,i=r.userConfig,a=Zi(r.loadLevelObj||r.levels[r.currentLevel],i.videoPreference),o=r.audioTracks[r.audioTrack],s=r.subtitleTracks[r.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){let e=this.timelinePos-t.timelineStart;if(e>=0){let n=t.duration;n&&e<n&&(c=e)}}let l=t.identifier,u=H(H({},i),{},{maxMaxBufferLength:Math.min(15,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:l,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:o||i.audioPreference,subtitlePreference:s||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));let d=u.cmcd;d!=null&&d.sessionId&&d.contentId&&(u.cmcd=V({},d,{contentId:df(t.uri)})),this.getAssetPlayer(l)&&this.warn(`Duplicate date range identifier ${e} and asset ${l}`);let f=new wp(this.HlsPlayerClass,u,e,t);this.playerQueue.push(f),e.assetList[n]=t;let p=!0,m=r=>{if(r.live){let t=Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:F.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},i=this.findEventIndex(e.identifier);this.handleAssetItemError(r,e,i,n,t.message);return}let i=r.edge-r.fragmentStart,a=t.duration;(p||a===null||i>a)&&(p=!1,this.log(`Interstitial asset "${l}" duration change ${a} > ${i}`),t.duration=i,this.updateSchedule())};f.on(L.LEVEL_UPDATED,(e,{details:t})=>m(t)),f.on(L.LEVEL_PTS_UPDATED,(e,{details:t})=>m(t)),f.on(L.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let h=(e,t)=>{let n=this.getAssetPlayer(l);if(n&&t.tracks){n.off(L.BUFFER_CODECS,h),n.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===n.assetItem&&e&&!n.media&&this.bufferAssetPlayer(n,e)}};f.on(L.BUFFER_CODECS,h),f.on(L.BUFFERED_TO_END,()=>{let t=this.getAssetPlayer(l);if(this.log(`buffered to end of asset ${t}`),!t||!this.schedule)return;let n=this.getEventItem(e.identifier);n&&this.advanceAssetBuffering(n,t.assetItem)});let g=t=>()=>{if(!this.getAssetPlayer(l)||!this.schedule)return;this.shouldPlay=!0;let n=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,t)};return f.once(L.MEDIA_ENDED,g(n)),f.once(L.PLAYOUT_LIMIT_REACHED,g(1/0)),f.on(L.ERROR,(t,r)=>{if(!this.schedule)return;let i=this.getAssetPlayer(l);if(r.details===I.BUFFER_STALLED_ERROR){if(i!=null&&i.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}r.details!==I.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(r,e,this.findEventIndex(e.identifier),n,`Asset player error ${r.error} ${e}`)}),f.on(L.DESTROYING,()=>{if(!this.getAssetPlayer(l)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${l}`),r={fatal:!0,type:F.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.findEventIndex(e.identifier),n,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Cp(t)}`),this.hls.trigger(L.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:n,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let n=this.playerQueue[t];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,t){let n=this.getAssetPlayerQueueIndex(e);if(n!==-1){let e=this.playerQueue[n];this.log(`clear ${e} toSegment: ${t&&Dp(t)}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(n,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,n,r,i){let{interstitial:a,assetItem:o,assetId:s}=e,c=a.assetList.length,l=this.playingAsset;this.endedAsset=null,this.playingAsset=o,l?.identifier!==s&&(l&&(this.clearAssetPlayer(l.identifier,n[r]),delete l.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${Cp(o)}`),this.hls.trigger(L.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:n.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){if(!this.schedule)return;let{interstitial:n,assetItem:r}=e,i=this.getEventItem(n.identifier);if(!i)return;if(e.loadSource(),this.setBufferingItem(i),this.bufferingAsset=r,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(i,r);return}let a=this.getBufferingPlayer();if(a===e)return;let o=n.appendInPlace;if(o&&a?.interstitial.appendInPlace===!1)return;let s=a?.tracks||this.detachedData?.tracks||this.requiredTracks;if(o&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(s&&!sn(s,e.tracks)){let t=Error(`Asset ${Cp(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(s)}')`),i={fatal:!0,type:F.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},a=n.findAssetIndex(r);this.handleAssetItemError(i,n,this.findEventIndex(n.identifier),a,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,n=this.primaryMedia;if(!t||!n)return;let r=n.currentTime,i=t.findAssetIndex(e,r),a=e.assetList[i];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let s=o.currentTime||r-a.timelineStart,c=o.duration-s;if(this.warn(`Stalled at ${s} of ${s+c} in ${o} ${e} (media.currentTime: ${r})`),s&&(c/n.playbackRate<.5||o.bufferedInPlaceToEnd(n,o.currentTime))&&o.hls){let n=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,i)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let n=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(n),t.currentTime=e):this.log(`Cannot ${n}`)}}handleAssetItemError(e,t,n,r,i){if(e.details===I.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Cp(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||``,s=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[s]||null,l=this.schedule.items,u=V({},e,{fatal:!1,errorAction:pa(!0),asset:a,assetListIndex:r,event:t,schedule:l,scheduleIndex:n,player:c});if(this.hls.trigger(L.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;let d=this.playingAsset,f=this.bufferingAsset,p=Error(i);if(a&&(this.clearAssetPlayer(o,null),a.error=p),!t.assetList.some(e=>!e.error))t.error=p;else for(let e=r;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d?.identifier===o?this.advanceAfterAssetEnded(t,n,r):f?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,n=this.effectivePlayingItem,r=this.playingItem,i=this.seekableStart,a=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(n)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Dp(n)} startPosition: ${a} seekableStart: ${i} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,i);let r=this.updateItem(n,o);this.itemsMatch(n,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||r&&!this.isInterstitial(r))return;let s=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(s)}onAssetListLoaded(e,t){var n;let r=t.event,i=r.identifier,a=t.assetListResponse.ASSETS;if(!((n=this.schedule)!=null&&n.hasEvent(i)))return;let o=r.timelineStart,s=r.duration,c=0;a.forEach((e,t)=>{let n=parseFloat(e.DURATION);this.createAsset(r,t,c,o+c,n,e.URI),c+=n}),r.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${s}) ${r}`);let l=this.waitingItem?.event.identifier===i;this.updateSchedule();let u=this.bufferingItem?.event;if(l){let e=this.findEventIndex(i),t=this.getEventItem(i);if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){r.error=Error(`Interstitial ${a.length?`no longer within playback range`:`asset-list is empty`} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if(u?.identifier===i){let e=r.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case I.ASSET_LIST_PARSING_ERROR:case I.ASSET_LIST_LOAD_ERROR:case I.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case I.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace){this.handleInPlaceStall(e.event);return}let t=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${t?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Mp=class{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var e;let{media:t}=this,n=this.levelDetails;if(!t||!n||!this.hls)return;this.currentTime=t.currentTime;let r=this.hls.config,i=this.computeLatency();if(i===null)return;this._latency=i;let{lowLatencyMode:a,maxLiveSyncPlaybackRate:o}=r;if(!a||o===1||!n.live)return;let s=this.targetLatency;if(s===null)return;let c=i-s,l=c<Math.min(this.maxLatency,s+n.targetduration),u=ks(r)&&!!((e=this.hls.interstitialsManager)!=null&&(e=e.playingItem)!=null&&e.event);if(l&&c>.05&&this.forwardBufferLength>1&&!u){let e=Math.min(2,Math.max(1,o)),n=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,r=Math.min(e,Math.max(1,n));this.changeMediaPlaybackRate(t,r)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.registerListeners()}get levelDetails(){return this.hls?.latestLevelDetails||null}get latency(){return this._latency||0}get maxLatency(){let e=this.hls?.config;if(!e)return 0;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:n,partHoldBack:r,targetduration:i}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:s}=t,c=this.hls.userConfig,l=s&&r||n;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=a===void 0?o*i:a);let u=i;return l+Math.min(this.stallCount*t.liveSyncOnStallIncrease,u)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;let n=this.levelDetails;if(n===null)return null;let r=n.edge,i=e-t-this.edgeStalled,a=r-n.totalduration,o=r-(this.hls.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(a,i),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null||!this.hls)return 0;let t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.ERROR,this.onError,this),e.on(L.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.ERROR,this.onError,this),e.off(L.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener(`timeupdate`,this.onTimeupdate)}onMediaDetaching(){this.media&&=(this.media.removeEventListener(`timeupdate`,this.onTimeupdate),null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener(`timeupdate`,this.onTimeupdate)}onAssetStarted(e,t){var n;let r=this.hls,i=this.media||t.event.appendInPlace&&(r==null||(n=r.interstitialsManager)==null?void 0:n.playerQueue.reduce((e,t)=>e||t.media,null));r&&i&&i.playbackRate>1&&i.playbackRate<=r.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(i,1)}onError(e,t){var n;t.details===I.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn(`[latency-controller]: Stall detected, adjusting target latency`))}changeMediaPlaybackRate(e,t){var n;e.playbackRate!==t&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${this.targetLatency?.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Np=500,Pp=1e-6,Fp=class extends Ds{constructor(e,t,n){super(e,t,n,`subtitle-stream-controller`,z.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(L.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(L.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Q.IDLE,this.setInterval(Np),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){var n,r;let{frag:i,part:a,success:o}=t;if(!o)return;let s=(n=this.tracksBuffered)[r=i.level]||(n[r]=[]);if(!s)return;let c,l=(a||i).start;for(let e=0;e<s.length;e++)if(l>=s[e].start&&l<=s[e].end){c=s[e];break}let u=l+(a||i).duration;if(c?c.end=u:(c={start:l,end:u},s.push(c)),!a||u>=i.end-Pp){let e=this.fragmentTracker.fragBuffered(i);a&&e&&(e.range.subs={time:[{startPTS:i.start,endPTS:u}],partial:!0}),Tt(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,a),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:n,endOffset:r}=t;if(n===0&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{if(t)for(let n=0;n<t.length;){if(t[n].end<=e){t.shift();continue}if(t[n].start<e)t[n].start=e;else break;n++}}),this.fragmentTracker.removeFragmentsInRange(n,e,z.SUBTITLE)}}onError(e,t){let n=t.frag;n?.type===z.SUBTITLE&&(t.details===I.FRAG_GAP&&this.fragmentTracker.addAsGap(n),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Q.STOPPED&&(this.state=Q.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Pl(this.levels,t)){this.levels=t.map(e=>new Mi(e));return}this.tracksBuffered=[],this.levels=t.map(e=>new Mi(e)),this.fragmentTracker.removeFragmentsInRange(0,1/0,z.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var n;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];if(!(r!=null&&r.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Q.STOPPED&&this.setInterval(Np)}onSubtitleTrackLoaded(e,t){var n;let{currentTrackId:r,levels:i}=this,{details:a,id:o}=t;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let s=i[o];if(o>=i.length||!s)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:``},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=this.mainDetails,l=0;if(a.live||(n=s.details)!=null&&n.live){if(a.deltaUpdateFailed)return;if(!c){this.startFragRequested=!1;return}s.details&&(l=this.alignPlaylists(a,s.details,this.levelLastLoaded?.details)),a.alignedSliding||(ws(c,a,this),l=a.fragmentStart)}s.details=a,this.levelLastLoaded=s,c&&!this.startFragRequested&&this.setStartPosition(c,l),o===r&&(this.hls.trigger(L.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:n,payload:r}=e;n&&r!=null&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,n)}_handleFragmentLoadComplete(e){let{frag:t,payload:n}=e;!this.fragContextChanged(t)&&n!=null&&n.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(n,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&ho(t.method))}decryptPayload(e,t,n){let r=t.decryptdata,i=performance.now();this.decrypter.decrypt(new Uint8Array(e),r.key.buffer,r.iv.buffer,go(r.method)).then(e=>{this.fragContextChanged(t)||this.hls.trigger(L.FRAG_DECRYPTED,{frag:t,part:n,payload:e,stats:{tstart:i,tdecrypt:performance.now()}})}).catch(e=>{this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:n}),n||(this.warn(`${e.name}: ${e.message}`),this.state=Q.IDLE)})}doTick(){if(this.state===Q.IDLE&&this.levels){if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:t,levels:n}=this,r=n[t],i=r?.details;if(!i||this.waitForLive(r)||this.waitForCdnTuneIn(i)){this.startFragRequested=!1;return}let{config:a}=this,o=this.playhead,s=J.bufferedInfo(this.tracksBuffered[t]||[],o,a.maxBufferHole),{end:c,len:l}=s;if(l>Math.max(this.hls.maxBufferLength+i.levelTargetDuration,this.hls.mainForwardBufferInfo?.len||0)||l&&!this.buffering)return;let u=this.getNextFragment(c,i);if(!u)return;if(Tt(u)){var e;if(u.end===s.end)return;let t=u.sn-i.startSN,n=i.fragments[t-1];u.cc===n?.cc&&!((e=i.partList)!=null&&e.length)&&this.fragmentTracker.getState(n)===Z.NOT_LOADED&&(u=n)}this.loadFragment(u,r,c)}}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);(r===Z.NOT_LOADED||r===Z.PARTIAL)&&super.loadFragment(e,t,n)}get mediaBufferTimeRanges(){return new Ip(this.tracksBuffered[this.currentTrackId]||[])}},Ip=class{constructor(e){this.buffered=void 0;let t=(t,n,r)=>{if(n>>>=0,n>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][t]};this.buffered={get length(){return e.length},end(n){return t(`end`,n,e.length)},start(n){return t(`start`,n,e.length)}}}},Lp={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Rp=e=>String.fromCharCode(Lp[e]||e),zp=15,Bp=42,Vp={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Hp={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Up={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Wp={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Gp=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`black`,`transparent`],Kp=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let n=typeof t==`function`?t():t;U.log(`${this.time} [${e}] ${n}`)}}},qp=function(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t},Jp=Object.freeze({foreground:`white`,underline:!1,italics:!1,background:`black`,flash:!1}),Yp=class{constructor(){this.styles=Jp}get foreground(){return this.styles.foreground}set foreground(e){let t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){let t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=Jp}setStyles(e){let t=this.styles,n=Object.prototype.hasOwnProperty;this.styles={foreground:n.call(e,`foreground`)?e.foreground:t.foreground,underline:n.call(e,`underline`)?e.underline:t.underline,italics:n.call(e,`italics`)?e.italics:t.italics,background:n.call(e,`background`)?e.background:t.background,flash:n.call(e,`flash`)?e.flash:t.flash}}toString(){return`color=`+this.foreground+`, underline=`+this.underline+`, italics=`+this.italics+`, background=`+this.background+`, flash=`+this.flash}},Xp=class{constructor(){this.uchar=` `,this.penState=new Yp}reset(){this.uchar=` `,this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}},Zp=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Yp,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Bp;e++)this.chars.push(new Xp);this.logger=e}equals(e){let t=this.chars,n=e.chars;for(let e=0;e<Bp;e++){let r=t[e],i=n[e];if(r.uchar!==i.uchar)return!1;let a=r.penState.styles,o=i.penState.styles;if(a!==o&&(a.foreground!==o.foreground||a.underline!==o.underline||a.italics!==o.italics||a.background!==o.background||a.flash!==o.flash))return!1}return!0}copy(e){for(let t=0;t<Bp;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<Bp;t++){let n=e[t];if(n.uchar!==` `)return!1;let r=n.penState.styles;if(r!==Jp&&(r.foreground!==`white`||r.underline||r.italics||r.background!==`black`||r.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,`Negative cursor position `+this.pos),this.pos=0):this.pos>=Bp&&(this.logger.log(3,`Too large cursor position `+this.pos),this.pos=41)}moveCursor(e){let t=Math.min(this.pos+e,Bp);if(e>1)for(let e=this.pos+1;e<t;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(` `,this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=Rp(e);if(this.pos>=Bp){this.logger.log(0,()=>`Cannot insert `+e.toString(16)+` (`+t+`) at position `+this.pos+`. Skipping it!`);return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Bp;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let n=0;n<Bp;n++){let r=this.chars[n].uchar;r!==` `&&(t=!1),e.push(r)}return t?``:e.join(``)}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Qp=class{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<zp;t++)this.rows.push(new Zp(e));this.logger=e}reset(){for(let e=0;e<zp;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let n=0;n<zp;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<zp;t++){let n=this.rows[t].chars,r=e.rows[t].chars;for(let e=0;e<Bp;e++){let t=n[e],i=r[e];t.uchar=i.uchar,t.penState.styles=i.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<zp;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,`setCursor: `+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>`pacData = `+q(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<zp;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){let r=n.rows[e].cueStartTime,i=this.logger.time;if(r!==null&&i!==null&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(n.rows[e+r])}}this.currRow=t;let n=this.rows[this.currRow];if(e.indent!==null){let t=e.indent,r=Math.max(t-1,0);n.setCursor(e.indent),e.color=n.chars[r].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:`black`,flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>`bkgData = `+q(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,`roll_up but nrRollUpRows not set yet`);return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,`Rolling up`)}getDisplayText(e){e||=!1;let t=[],n=``,r=-1;for(let n=0;n<zp;n++){let i=this.rows[n].getTextString();i&&(r=n+1,e?t.push(`Row `+r+`: '`+i+`'`):t.push(i.trim()))}return t.length>0&&(n=e?`[`+t.join(` | `)+`]`:t.join(`
|
|
46
|
-
`)),n}getTextAndFormat(){return this.rows}},$p=class{constructor(e,t,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Qp(n),this.nonDisplayedMemory=new Qp(n),this.lastOutputScreen=new Qp(n),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>`MODE=`+e),this.mode===`MODE_POP-ON`?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!==`MODE_ROLL-UP`&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?`DISP`:`NON_DISP`;this.logger.log(2,()=>t+`: `+this.writeScreen.getDisplayText(!0)),(this.mode===`MODE_PAINT-ON`||this.mode===`MODE_ROLL-UP`)&&(this.logger.log(1,()=>`DISPLAYED: `+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,`RCL - Resume Caption Loading`),this.setMode(`MODE_POP-ON`)}ccBS(){this.logger.log(2,`BS - BackSpace`),this.mode!==`MODE_TEXT`&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,`DER- Delete to End of Row`),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,`RU(`+e+`) - Roll Up`),this.writeScreen=this.displayedMemory,this.setMode(`MODE_ROLL-UP`),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,`FON - Flash On`),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,`RDC - Resume Direct Captioning`),this.setMode(`MODE_PAINT-ON`)}ccTR(){this.logger.log(2,`TR`),this.setMode(`MODE_TEXT`)}ccRTD(){this.logger.log(2,`RTD`),this.setMode(`MODE_TEXT`)}ccEDM(){this.logger.log(2,`EDM - Erase Displayed Memory`),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,`CR - Carriage Return`),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,`ENM - Erase Non-displayed Memory`),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,`EOC - End Of Caption`),this.mode===`MODE_POP-ON`){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>`DISP: `+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,`TO(`+e+`) - Tab Offset`),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};t.underline=e%2==1,t.italics=e>=46,t.foreground=t.italics?`white`:[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`][Math.floor(e/2)-16],this.logger.log(2,`MIDROW: `+q(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},em=class{constructor(e,t,n){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=rm(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Kp,this.field=e,this.outputFilters=[null,t,n]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var n;this.outputFilters[e]=t,(n=this.channels[e])==null||n.setHandler(t)}getChannel(e){let t=this.channels[e];return t||=this.channels[e]=new $p(this.field+e-1,this.outputFilters[e],this.logger),t}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){let n=t[e]&127,r=t[e+1]&127,i=!1,a=null;if(n===0&&r===0)continue;this.logger.log(3,()=>`[`+qp([t[e],t[e+1]])+`] -> (`+qp([n,r])+`)`);let o=this.cmdHistory;if(n>=16&&n<=31){if(nm(n,r,o)){tm(null,null,o),this.logger.log(3,()=>`Repeated command (`+qp([n,r])+`) is dropped`);continue}tm(n,r,this.cmdHistory),i=this.parseCmd(n,r),i||=this.parseMidrow(n,r),i||=this.parsePAC(n,r),i||=this.parseBackgroundAttributes(n,r)}else tm(null,null,o);if(!i&&(a=this.parseChars(n,r),a)){let e=this.currentChannel;e&&e>0?this.getChannel(e).insertChars(a):this.logger.log(2,`No channel found yet. TEXT-MODE?`)}!i&&!a&&this.logger.log(2,()=>`Couldn't parse cleaned data `+qp([n,r])+` orig: `+qp([t[e],t[e+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;let n=e===20||e===21||e===23?1:2,r=this.getChannel(n);return e===20||e===21||e===28||e===29?t===32?r.ccRCL():t===33?r.ccBS():t===34?r.ccAOF():t===35?r.ccAON():t===36?r.ccDER():t===37?r.ccRU(2):t===38?r.ccRU(3):t===39?r.ccRU(4):t===40?r.ccFON():t===41?r.ccRDC():t===42?r.ccTR():t===43?r.ccRTD():t===44?r.ccEDM():t===45?r.ccCR():t===46?r.ccENM():t===47&&r.ccEOC():r.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(n=e===17?1:2,n!==this.currentChannel)return this.logger.log(0,`Mismatch channel in midrow parsing`),!1;let r=this.channels[n];return r?(r.ccMIDROW(t),this.logger.log(3,()=>`MIDROW (`+qp([e,t])+`)`),!0):!1}return!1}parsePAC(e,t){let n;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;let r=e<=23?1:2;return n=t>=64&&t<=95?r===1?Vp[e]:Up[e]:r===1?Hp[e]:Wp[e],this.getChannel(r).setPAC(this.interpretPAC(n,t)),this.currentChannel=r,!0}interpretPAC(e,t){let n,r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=(n&1)==1,n<=13?r.color=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`white`][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color=`white`):r.indent=Math.floor((n-16)/2)*4,r}parseChars(e,t){let n,r=null,i=null;if(e>=25?(n=2,i=e-8):(n=1,i=e),i>=17&&i<=19){let e;e=i===17?t+80:i===18?t+112:t+144,this.logger.log(2,()=>`Special char '`+Rp(e)+`' in channel `+n),r=[e]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>`Char codes = `+qp(r).join(`,`)),r}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let n,r={};e===16||e===24?(n=Math.floor((t-32)/2),r.background=Gp[n],t%2==1&&(r.background+=`_semi`)):t===45?r.background=`transparent`:(r.foreground=`black`,t===47&&(r.underline=!0));let i=e<=23?1:2;return this.getChannel(i).setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}tm(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let n=this.channels[t];n&&n.cueSplitAtTime(e)}}};function tm(e,t,n){n.a=e,n.b=t}function nm(e,t,n){return n.a===e&&n.b===t}function rm(){return{a:null,b:null}}var im=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},am=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=sm(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(L.FRAG_LOADING,this.onFragLoading,this),e.on(L.FRAG_LOADED,this.onFragLoaded,this),e.on(L.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(L.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(L.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(L.FRAG_LOADING,this.onFragLoading,this),e.off(L.FRAG_LOADED,this.onFragLoaded,this),e.off(L.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(L.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(L.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new im(this,`textTrack1`),t=new im(this,`textTrack2`),n=new im(this,`textTrack3`),r=new im(this,`textTrack4`);this.cea608Parser1=new em(1,e,t),this.cea608Parser2=new em(3,n,r)}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=om(r[0],r[1],t,n);if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),a=!0,o/(n-t)>.5))return}if(a||i.push([t,n]),this.config.renderTextTracksNatively){let i=this.cueCache[e];if(i){let e=this.Cues.newCue(null,t,n,r);e.length&&i.push.apply(i,e)}else{let i=this.captionsTracks[e].track;this.Cues.newCue(i,t,n,r)}}else{let i=this.Cues.newCue(null,t,n,r),a=this.captionsProperties[e]?.media;this.hls.trigger(L.CUES_PARSED,{type:`captions`,cues:i,track:e,closedCaptions:a})}}onInitPtsFound(e,{id:t,timestampOffsets:n}){let{unparsedFrags:r}=this;t===z.MAIN&&(this.initPTS=n),r.length&&(this.unparsedFrags=[],r.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(L.FRAG_LOADED,e):this.hls.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:Error(`Subtitle discontinuity domain does not match main`)})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:n,cueCache:r,media:i}=this,{label:a,languageCode:o}=t[e];i&&(r[e]=[],n[e]=Mf(i,`captions`,a,o,`hidden`))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let n={_id:e,label:t.label,kind:`captions`,default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(L.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let n=!!t.transferMedia;if(this.media=null,!n){if(this.config.renderTextTracksNatively){let{captionsTracks:e,cueCache:t}=this;for(let n in e)e[n].remove(),delete t[n]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=sm(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let n=t.subtitleTracks||[];if(n.length&&!this.config.renderTextTracksNatively&&!Pl(this.tracks,n)){let e=n.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(L.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}this.tracks=n}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){return this.hls.levels[e.level]?.attrs[`CLOSED-CAPTIONS`]}onFragLoading(e,t){if(this.enabled&&t.frag.type===z.MAIN){let{cea608Parser1:e,cea608Parser2:n,lastSn:r}=this,{cc:i,sn:a}=t.frag,o=t.part?.index??-1;e&&n&&(a!==r+1||a===r&&o!==this.lastPartIndex+1||i!==this.lastCc)&&(e.reset(),n.reset()),this.lastCc=i,this.lastSn=a,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:n,payload:r}=t;if(n.level<this.tracks.length&&n.type===z.SUBTITLE){var i;if(r.byteLength||(i=n.initSegment)!=null&&(i=i.data)!=null&&i.byteLength){let e=n.decryptdata,r=`stats`in t;if(e==null||!e.encrypted||r){let e=this.tracks[n.level],r=this.vttCCs;r[n.cc]||(r[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e?.textCodec===gf?this._parseIMSC1(t):this._parseVTTs(t)}}else{let e=`part`in t?t.part:null;this.hls.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:e,error:Error(`Empty subtitle payload`)})}}}_parseIMSC1(e){let{frag:t,payload:n}=e,r=`part`in e?e.part:null;if(!this.initPTS[t.cc]){this.unparsedFrags.push(e);return}let i=this.hls;bf(n,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),i.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},e=>{i.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${e}`),i.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:e})})}_parseVTTs(e){let{frag:t,payload:n}=e,r=`part`in e?e.part:null,{initPTS:i,unparsedFrags:a}=this,o=i.length-1;if(!i[t.cc]&&o===-1){a.push(e);return}let s=this.hls,c=t.initSegment?.data;hf(c?Tr(c,new Uint8Array(n)).buffer:n,this.initPTS[t.cc],this.vttCCs,t.cc,(r&&!c?r:t).start,e=>{this._appendCues(e,t.level),s.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},n=>{let i=n.message.startsWith(`Missing initPTS`);if(s.logger.log(`${i?`Deferred parsing of`:`Cannot parse`} VTT cue (sn: ${t.sn} @${t.start}): ${n}`),i){a.push(e);return}this.config.enableIMSC1&&this._fallbackToIMSC1(e),s.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:n})})}_fallbackToIMSC1(e){let{frag:t,payload:n}=e,r=this.tracks[t.level];r.textCodec||bf(n,this.initPTS[t.cc],()=>{r.textCodec=gf,this._parseIMSC1(e)},()=>{r.textCodec=`wvtt`})}_appendCues(e,t){let n=this.hls;if(this.config.renderTextTracksNatively){let n=this.tracks[t].trackNode?.track;if(!n||n.mode===`disabled`)return;e.forEach(e=>Pf(n,e))}else{let r=this.tracks[t];if(!r)return;let i=r.default?`default`:`subtitles`+t;n.trigger(L.CUES_PARSED,{type:`subtitles`,cues:e,track:i,subtitleTrack:r})}}onFragDecrypted(e,t){let{frag:n}=t;n.type===z.SUBTITLE&&this.onFragLoaded(L.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:n,samples:r}=t;if(n.type!==z.MAIN||this.closedCaptionsForLevel(n)!==`NONE`)for(let e=0;e<r.length;e++){let t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();let n=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,n[0]),this.cea608Parser2.addData(r[e].pts,n[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var n;let{type:e,timeRanges:r}=t;if(e===`video`&&(n=r[e])!=null&&n.length){let{captionsTracks:e,cueCache:t}=this;Object.keys(t).forEach(n=>{let r=e[n]?.track;if(r){let e=t[n];for(let t=0;t<e.length;t++)Pf(r,e[t])}delete t[n]})}}}onBufferFlushing(e,t){let{startOffset:n,endOffset:r,endOffsetSubtitles:i,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<r)){if(!a||a===`video`){let{captionsTracks:e,cueCache:t}=this;Object.keys(e).forEach(t=>Ff(e[t].track,n,r)),Object.keys(t).forEach(e=>{let i=t[e];for(let e=i.length;e--;){let t=i[e];t.startTime>=n&&t.endTime<=r&&i.splice(e,1)}})}this.config.renderTextTracksNatively&&n===0&&i!==void 0&&this.tracks.forEach(e=>{let t=e.trackNode?.track;t&&Ff(t,n,i)})}}extractCea608Data(e){let t=[[],[]],n=e[0]&31,r=2;for(let i=0;i<n;i++){let n=e[r++],i=127&e[r++],a=127&e[r++];if((i!==0||a!==0)&&4&n){let e=3&n;(e===0||e===1)&&(t[e].push(i),t[e].push(a))}}return t}};function om(e,t,n,r){return Math.min(t,r)-Math.max(e,n)}function sm(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var cm=/\s/,lm={newCue(e,t,n,r){let i=[],a,o,s,c,l,u=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(a=r.rows[f],s=!0,c=0,l=``,!a.isEmpty()){var d;for(let e=0;e<a.chars.length;e++)cm.test(a.chars[e].uchar)&&s?c++:(l+=a.chars[e].uchar,s=!1);a.cueStartTime=t,t===n&&(n+=1e-4),c>=16?c--:c++;let r=lf(l.trim()),p=mf(t,n,r);e!=null&&(d=e.cues)!=null&&d.getCueById(p)||(o=new u(t,n,r),o.id=p,o.line=f+1,o.align=`left`,o.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(o))}return e&&i.length&&(i.sort((e,t)=>e.line===`auto`||t.line===`auto`?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>Pf(e,t))),i}},um=class{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new Ct}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,n){let r=this.stats;if(r.loading.start)throw Error(`Loader can only be used once.`);r.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Wt(e,t,!0))this.retry(e);else{U.warn(`timeout while loading ${this.context?.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:n}=this;this.retryDelay=Ht(e,n.retry),n.retry++,U.warn(`${status?`HTTP Status `+status:`Timeout`} while loading ${t?.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function dm(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var fm=/(\d+)-(\d+)\/(\d+)/,pm=class extends um{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||_m}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){let{config:e,context:t,stats:n}=this;if(!e||!t)return;n.loading.first=0,n.loaded=0,n.aborted=!1,this.controller=new self.AbortController;let r=mm(t,this.controller.signal),i=t.responseType===`arraybuffer`,a=i?`byteLength`:`length`,{maxTimeToFirstByteMs:o,maxLoadTimeMs:s}=e.loadPolicy;this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&P(o)?o:s,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(El(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{this.response=r;let a=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=s,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},s-(a-n.loading.start)),!r.ok){let{status:e,statusText:t}=r;throw new vm(t||`fetch, bad network response`,e,r)}n.loading.first=a,n.total=gm(r.headers)||n.total;let o=this.callbacks?.onProgress;return o&&P(e.highWaterMark)?this.loadProgressively(r,n,t,e.highWaterMark,o):i?r.arrayBuffer():t.responseType===`json`?r.json():r.text()}).then(r=>{var i;let o=this.response;if(!o)throw Error(`loader destroyed`);self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);let s=r[a];s&&(n.loaded=n.total=s);let c={url:o.url,data:r,code:o.status},l=this.callbacks?.onProgress;l&&!P(e.highWaterMark)&&l(n,t,r,o),(i=this.callbacks)==null||i.onSuccess(c,n,t,o)}).catch(r=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;let i=r&&r.code||0,a=r?r.message:null,o=e.loadPolicy.errorRetry,s=n.retry;if(Wt(o,s,!1,{url:t.url,data:void 0,code:i}))this.retry(o);else{var c;U.error(`${i} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:i,text:a},t,r?r.details:null,n)}})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,n,r=0,i){let a=new As,o=e.body.getReader(),s=()=>o.read().then(o=>{if(o.done)return a.dataLength&&i(t,n,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=o.value,l=c.length;return t.loaded+=l,l<r||a.dataLength?(a.push(c),a.dataLength>=r&&i(t,n,a.flush().buffer,e)):i(t,n,c.buffer,e),s()}).catch(()=>Promise.reject());return s()}};function mm(e,t){let n={method:`GET`,mode:`cors`,credentials:`same-origin`,signal:t,headers:new self.Headers(V({},e.headers))};return e.rangeEnd&&n.headers.set(`Range`,`bytes=`+e.rangeStart+`-`+String(e.rangeEnd-1)),n}function hm(e){let t=fm.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function gm(e){let t=e.get(`Content-Range`);if(t){let e=hm(t);if(P(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function _m(e,t){return new self.Request(e.url,t)}var vm=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},ym=(e,t,n)=>Math.max(t,Math.min(e,n)),bm=/^age:\s*[\d.]+\s*$/im,xm=class extends um{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return i.call(this,n,t.url,t)}).catch(e=>{if(!(this.loader!==n||this.stats.aborted))return n.open(`GET`,t.url,!0),i.call(this,n,t.url,t)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,t,e)}).catch(e=>{var i;(i=this.callbacks)==null||i.onError({code:n.status,text:e.message},t,n,r)}):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open(`GET`,t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=n.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader(`Range`,`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&P(i)?i:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:n}=this;if(!e||!t)return;let r=t.readyState,i=this.config;if(!n.aborted&&r>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,s=t.responseType===`text`?t.responseText:null;if(r>=200&&r<300){let i=s??t.response;if(i!=null){var a;n.loading.end=Math.max(self.performance.now(),n.loading.first);let o=t.responseType===`arraybuffer`?i.byteLength:i.length;n.loaded=n.total=o,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);let s=this.callbacks?.onProgress;s&&s(n,e,i,t);let c={url:t.responseURL,data:i,code:r};e.rangeEnd&&o!==e.rangeEnd-e.rangeStart&&U.warn(`Payload length ${o} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(a=this.callbacks)==null||a.onSuccess(c,n,e,t);return}}let c=i.loadPolicy.errorRetry,l=n.retry;if(Wt(c,l,!1,{url:e.url,data:void 0,code:r}))this.retry(c);else{var o;U.error(`${r} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:r,text:t.statusText},e,t,n)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&bm.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,`im`).test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},Sm=H(H({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:`edge`,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:xm,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:`process`,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Oo,requireKeySystemAccessOnStart:!1,reuseKeySessions:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:rp,abrController:Qi,bufferController:wa,capLevelController:Ll,errorController:ua,fpsController:$d,id3TrackController:Xf,gapController:Vf,latencyController:Mp},Cm()),{},{subtitleStreamController:Fp,subtitleTrackController:Rf,timelineController:am,audioStreamController:Ml,audioTrackController:Il,emeController:qd,cmcdController:Bd,contentSteeringController:Hd,iframeController:dp,interstitialsController:jp});function Cm(){return{cueHandler:lm,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:`English`,captionsTextTrack1LanguageCode:`en`,captionsTextTrack2Label:`Spanish`,captionsTextTrack2LanguageCode:`es`,captionsTextTrack3Label:`Unknown CC`,captionsTextTrack3LanguageCode:``,captionsTextTrack4Label:`Unknown CC`,captionsTextTrack4LanguageCode:``,renderTextTracksNatively:!0}}function wm(e,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error(`Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration`);if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error(`Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"`);if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error(`Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"`);if(t.liveMaxUnchangedPlaylistRefresh!==void 0){let e=t.liveMaxUnchangedPlaylistRefresh,r=ym(e,2,1/0);r!==e&&n.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${e} to ${r}.`),t.liveMaxUnchangedPlaylistRefresh=r}let r=Tm(e),i=[`manifest`,`level`,`frag`],a=[`TimeOut`,`MaxRetry`,`RetryDelay`,`MaxRetryTimeout`];return i.forEach(e=>{let i=`${e===`level`?`playlist`:e}LoadPolicy`,o=t[i]===void 0,s=[];a.forEach(n=>{let a=`${e}Loading${n}`,c=t[a];if(c!==void 0&&o){s.push(a);let e=r[i].default;switch(t[i]={default:e},n){case`TimeOut`:e.maxLoadTimeMs=c,e.maxTimeToFirstByteMs=c;break;case`MaxRetry`:e.errorRetry.maxNumRetry=c,e.timeoutRetry.maxNumRetry=c;break;case`RetryDelay`:e.errorRetry.retryDelayMs=c,e.timeoutRetry.retryDelayMs=c;break;case`MaxRetryTimeout`:e.errorRetry.maxRetryDelayMs=c,e.timeoutRetry.maxRetryDelayMs=c}}}),s.length&&n.warn(`hls.js config: "${s.join(`", "`)}" setting(s) are deprecated, use "${i}": ${q(t[i])}`)}),H(H({},r),t)}function Tm(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(Tm):Object.keys(e).reduce((t,n)=>(t[n]=Tm(e[n]),t),{}):e}function Em(e,t){let n=e.loader;n!==pm&&n!==xm?(t.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):dm()&&(e.loader=pm,e.progressive=!0,e.enableSoftwareAES=!0,t.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var Dm=class extends Nl{constructor(e,t){super(e,`level-controller`),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this),e.on(L.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this),e.off(L.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let n=this.hls.config.preferManagedMediaSource,r=[],i={},a={},o=!1,s=!1,c=!1,l=!1;t.levels.forEach(e=>{let t=e.attrs,u=Am(e,n),{audioCodec:d,videoCodec:f,imageCodec:p,width:m,height:h}=e;if(!u){this.log(`Some or all CODECS not supported "${t.CODECS}"`);return}o||=!!(m&&h),s||=!!f,c||=!!d,l||=!!p;let{CODECS:g,"FRAME-RATE":_,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:b,"VIDEO-RANGE":x}=t,S=`${`${y||`.`}-`}${e.bitrate}-${b}-${_}-${g}-${x}-${v}`;if(!i[S]){let t=this.createLevel(e);i[S]=t,a[S]=1,r.push(t)}else if(i[S].uri!==e.url&&!e.attrs[`PATHWAY-ID`]){let t=a[S]+=1;e.attrs[`PATHWAY-ID`]=Array(t+1).join(`.`);let n=this.createLevel(e);i[S]=n,r.push(n)}else e.iframes||(i[S].addGroupId(`audio`,t.AUDIO),i[S].addGroupId(`text`,t.SUBTITLES))}),this.filterAndSortMediaOptions(r,t,o,s,c,l)}createLevel(e){let t=new Mi(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!km(n.videoCodec,this.hls.config.preferManagedMediaSource)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(e.message),t.supportedResult=gi(e,[])}return t}filterAndSortMediaOptions(e,t,n,r,i,a){let o=[],s=[],c=e,l=t.stats?.parsing||{},u=this.hls.config.preferManagedMediaSource;if((n||r)&&i&&(c=c.filter(({videoCodec:e,videoRange:t,width:n,height:r})=>(!!e||!!(n&&r))&&Oi(t))),r&&a&&(c=c.filter(e=>!e.imageCodec)),c.length===0){Promise.resolve().then(()=>{if(this.hls){let e=`no level with compatible codecs found in manifest`,n=e;t.levels.length&&(n=`one or more CODECS in variant not supported: ${q(t.levels.map(e=>e.attrs.CODECS).filter((e,t,n)=>n.indexOf(e)===t))}`,this.warn(n),e+=` (${n})`);let r=Error(e);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:n})}}),l.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(e=>!e.audioCodec||Om(e.audioCodec,u)),jm(o)),t.subtitles&&(s=t.subtitles,jm(s));let d=c.slice(0);c.sort((e,t)=>{if(e.attrs[`HDCP-LEVEL`]!==t.attrs[`HDCP-LEVEL`])return(e.attrs[`HDCP-LEVEL`]||``)>(t.attrs[`HDCP-LEVEL`]||``)?1:-1;if(n&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Di.indexOf(e.videoRange)-Di.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let n=ei(e.videoCodec),r=ei(t.videoCodec);if(n!==r)return r-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let n=ti(e.codecSet),r=ti(t.codecSet);if(n!==r)return r-n}return e.averageBitrate===t.averageBitrate?0:e.averageBitrate-t.averageBitrate});let f=d[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==d.length)){for(let e=0;e<d.length;e++)if(d[e].pathwayId===c[0].pathwayId){f=d[e];break}}this._levels=c;for(let e=0;e<c.length;e++)if(c[e]===f){this._firstLevel=e;let t=f.bitrate,n=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${t}`),this.hls.userConfig?.abrEwmaDefaultEstimate===void 0){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>n&&n===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let p=t.iframeVariants.filter(e=>Am(e,u));this._iframeVariants=p;let m=i&&!r,h=this.hls.config,g=!!(h.audioStreamController&&h.audioTrackController),_={levels:c,audioTracks:o,subtitleTracks:s,iframeVariants:p,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:r,altAudio:g&&!m&&o.some(e=>!!e.url)};l.end=performance.now(),this.hls.trigger(L.MANIFEST_PARSED,_)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let n=Error(`invalid level idx`),r=e<0;if(this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}let n=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs[`PATHWAY-ID`]:void 0,a=t[e],o=a.attrs[`PATHWAY-ID`];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&r&&i===o)return;this.log(`Switching to level ${e} (${a.height?a.height+`p `:``}${a.videoRange?a.videoRange+` `:``}${a.codecSet?a.codecSet+` `:``}@${a.bitrate})${o?` with Pathway `+o:``} from level ${n}${i?` with Pathway `+i:``}`);let s={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(L.LEVEL_SWITCHING,s);let c=a.details;if(!c||c.live){let e=this.switchParams(a.uri,r?.details,c);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e===void 0?this.hls.firstAutoLevel:e}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),n=e.filter(e=>t.indexOf(e)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=n}}onError(e,t){!t.fatal&&t.context&&t.context.type===R.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===z.MAIN){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var n;let{level:r,details:i}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let e=a.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else(n=t.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,i=e.attrs[`PATHWAY-ID`],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${i?` Pathway `+i:``}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${n}`),this.hls.trigger(L.LEVEL_LOADING,{url:n,level:r,levelInfo:e,pathwayId:e.attrs[`PATHWAY-ID`],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex===-1?this.hls.nextAutoLevel:this.manualLevelIndex}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let n=this.hls.config.abrSwitchInterval;if(n>0){let r=performance.now(),i=r-this.lastABRSwitchTime,a=n*1e3;if(this.lastABRSwitchTime>-1&&i<a){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(i)}ms < ${a}ms / ${n}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(i)}ms >= ${a}ms / ${n}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let n=this._levels.filter((t,n)=>n!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));_s(n),this._levels=n,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=n.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&=Math.min(this._startLevel,r),this.hls.trigger(L.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(L.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}};function Om(e,t){return Zr(e,`audio`,t)}function km(e,t){return Zr(e,`video`,t)}function Am(e,t){let{audioCodec:n,videoCodec:r}=e;n&&(e.audioCodec=n=ai(n,t)||void 0),r&&=e.videoCodec=li(r);let{unknownCodecs:i}=e;return!(i?.length||n&&!Om(n,t)||r&&!km(r,t))}function jm(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}var Mm=class extends Xt{constructor(e,t){super(`key-loader`,t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let t in this.keyLoaderInfo){let n=this.keyLoaderInfo[t].loader;if(n){if(e&&e!==n.context?.frag.type)return;n.abort()}}}destroy(){for(let e in this.keyLoaderInfo){let t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,n){return this.emeController?this.emeController.loadClear(e,t,n):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(n=>this.loadInternal(e,t,n)):this.loadInternal(e,t)}loadInternal(e,t,n){n&&e.setKeyFormat(n);let r=e.decryptdata;if(!r){let t=Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,t))}let i=e;switch(r.method){case`SAMPLE-AES`:case`SAMPLE-AES-CENC`:case`SAMPLE-AES-CTR`:return r.keyFormat===`identity`?this.loadKeyHTTP(i):t?t.then(()=>this.loadKeyEME(i)):this.loadKeyEME(i);case`AES-128`:case`AES-256`:case`AES-256-CTR`:return this.loadKeyHTTP(i);default:return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let t=hr(e.initSegment.data);if(t.length){let n=t[0],r=e.decryptdata.uri;if(n.some(e=>e!==0))this.log(`Using keyId found in init segment ${Hn(n)} keyUri: ${r}`),Po.setKeyIdForUri(r,n);else{let e=Po.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Hn(e)} keyUri: ${r}`),n=e}e.decryptdata.keyId=n}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,n=t.uri;if(!n)return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,Error(`Invalid key URI: "${n}"`)));let r=this.keyLoaderInfo[n];if(r){if(r.decryptdata.key)return t.key=r.decryptdata.key,r.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:r});if(r.keyLoadPromise)return r.keyLoadPromise.then(n=>(t.key=r.decryptdata.key,H(H({},n),{},{frag:e})))}this.log(`Loading${t.keyId?` keyId: `+Hn(t.keyId):``} URI: ${t.uri} from ${e.type} ${e.level}`);let i=this.config,a=i.loader,o=new a(i);e.keyLoader=o;let s=this.keyLoaderInfo[n]={decryptdata:t,keyLoadPromise:null,loader:o};return s.keyLoadPromise=new Promise((t,r)=>{let a={type:R.KEY,keyInfo:s,frag:e,responseType:`arraybuffer`,url:n},c=i.keyLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};o.load(a,l,{onSuccess:(e,n,i,a)=>{let{frag:o,keyInfo:s,url:c}=i;if(!o.decryptdata||s!==this.keyLoaderInfo[c])return this.resetLoader(i),r(Nm(o,I.KEY_LOAD_ERROR,Error(`after key load, decryptdata unset or changed`),a));s.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=s.loader=s.keyLoadPromise=null,t({frag:o,keyInfo:s})},onError:(t,i,a,o)=>{this.resetLoader(i),r(Nm(e,I.KEY_LOAD_ERROR,Error(`HTTP Error ${t.code} loading key ${t.text}`),a,H({url:n,data:void 0},t)))},onTimeout:(t,n,i)=>{this.resetLoader(n),r(Nm(e,I.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),i))},onAbort:(t,n,i)=>{this.resetLoader(n),r(Nm(e,I.INTERNAL_ABORTED,Error(`key loading aborted`),i))}})})}resetLoader(e){let{frag:t,keyInfo:n,url:r}=e,i=n.loader;t.keyLoader===i&&(t.keyLoader=n.loader=n.keyLoadPromise=null),delete this.keyLoaderInfo[r],i&&i.destroy()}};function Nm(e,t=I.KEY_LOAD_ERROR,n,r,i){return new Xa({type:F.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r||null})}function Pm(e){let{type:t}=e;switch(t){case R.AUDIO_TRACK:return z.AUDIO;case R.SUBTITLE_TRACK:return z.SUBTITLE;default:return z.MAIN}}function Fm(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var Im=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(L.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_LOADING,this.onLevelLoading,this),e.off(L.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(L.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,n=t.pLoader,r=t.loader,i=new(n||r)(t);return this.loaders[e.type]=i,i}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:`text`,type:R.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:n,level:r,pathwayId:i,url:a,deliveryDirectives:o,levelInfo:s}=t;this.load({id:n,level:r,pathwayId:i,responseType:`text`,type:R.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:s})}onAudioTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:R.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:R.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let n=this.loaders[R.LEVEL];if(n){let e=n.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(n.abort(),delete this.loaders[R.LEVEL])}}load(e){let t=this.hls.config,n=this.getInternalLoader(e);if(n){let t=this.hls.logger,r=n.context;if(r?.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives)){r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`);return}t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(r=e.type===R.MANIFEST?t.manifestLoadPolicy.default:V({},t.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),P(e.deliveryDirectives?.part)){let t;if(e.type===R.LEVEL&&e.level!==null?t=this.hls.levels[e.level].details:e.type===R.AUDIO_TRACK&&e.id!==null?t=this.hls.audioTracks[e.id].details:e.type===R.SUBTITLE_TRACK&&e.id!==null&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,n=t.targetduration;if(e&&n){let t=Math.max(e*3,n*.8)*1e3;r=V({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}let i=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0};n.load(e,a,{onSuccess:(e,t,n,r)=>{let i=this.getInternalLoader(n);this.resetInternalLoader(n.type);let a=e.data;t.parsing.start=performance.now(),Uo.isMediaPlaylist(a)||n.type!==R.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,n,r||null,i):this.handleMasterPlaylist(e,t,n,r)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}})}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?`auto`:`force`} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,n,r){let i=this.hls,a=e.data,o=Fm(e,n),s=Uo.parseMasterPlaylist(a,o);if(s.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,n,s.playlistParsingError,r,t);return}let{contentSteering:c,levels:l,iframeVariants:u,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m}=s;this.variableList=m,l.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:n}=this.hls.config,{audioCodec:r,videoCodec:i}=e;for(let a=t.length;a--;){let o=t[a];Zr(o,`audio`,n)?(e.audioCodec=r=r?`${r},${o}`:o,Yr.audio[r.substring(0,4)]=2,t.splice(a,1)):Zr(o,`video`,n)&&(e.videoCodec=i=i?`${i},${o}`:o,Yr.video[i.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:h=[],SUBTITLES:g,"CLOSED-CAPTIONS":_}=Uo.parseMasterPlaylistMedia(a,o,s);h.length&&!h.some(e=>!e.url)&&l[0].audioCodec&&!l[0].attrs.AUDIO&&(this.hls.logger.log(`[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one`),h.unshift({type:`main`,name:`main`,groupId:`main`,default:!1,autoselect:!1,forced:!1,id:-1,attrs:new so({}),bitrate:0,url:``})),i.trigger(L.MANIFEST_LOADED,{levels:l,audioTracks:h,subtitles:g,iframeVariants:u,captions:_,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m})}handleTrackOrLevelPlaylist(e,t,n,r,i){let a=this.hls,{id:o,level:s,type:c}=n,l=Fm(e,n),u=P(s)?s:P(o)?o:0,d=Pm(n),f=Uo.parseLevelPlaylist(e.data,l,u,d,0,this.variableList);if(c===R.MANIFEST){let e={attrs:new so({}),bitrate:0,details:f,name:``,url:l};f.requestScheduled=t.loading.start+ps(f,0),a.trigger(L.MANIFEST_LOADED,{levels:[e],audioTracks:[],iframeVariants:[],url:l,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,i)}handleManifestParsingError(e,t,n,r,i){this.hls.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.MANIFEST_PARSING_ERROR,fatal:t.type===R.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,n=!1,r,i){let a=`A network ${n?`timeout`:`error`+(r?` (status `+r.code+`)`:``)} occurred while loading ${e.type}`;e.type===R.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===R.AUDIO_TRACK||e.type===R.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let s=I.UNKNOWN,c=!1,l=this.getInternalLoader(e);switch(e.type){case R.MANIFEST:s=n?I.MANIFEST_LOAD_TIMEOUT:I.MANIFEST_LOAD_ERROR,c=!0;break;case R.LEVEL:s=n?I.LEVEL_LOAD_TIMEOUT:I.LEVEL_LOAD_ERROR,c=!1;break;case R.AUDIO_TRACK:s=n?I.AUDIO_TRACK_LOAD_TIMEOUT:I.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case R.SUBTITLE_TRACK:s=n?I.SUBTITLE_TRACK_LOAD_TIMEOUT:I.SUBTITLE_LOAD_ERROR,c=!1}l&&this.resetInternalLoader(e.type);let u={type:F.NETWORK_ERROR,details:s,fatal:c,url:e.url,loader:l,context:e,error:o,networkDetails:t,stats:i};if(r){let n=e.url;t&&`url`in t&&(n=t.url),u.response=H({url:n,data:void 0},r)}this.hls.trigger(L.ERROR,u)}handlePlaylistLoaded(e,t,n,r,i,a){let o=this.hls,{type:s,level:c,levelOrTrack:l,id:u,groupId:d,deliveryDirectives:f}=r,p=Fm(t,r),m=Pm(r),h=typeof r.level==`number`&&m===z.MAIN?c:void 0;l&&`iframes`in l&&l.iframes&&!e.iframesOnly&&(e.playlistParsingError=Error(`EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag`),e.iframesOnly=!0);let g=e.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:g,reason:g.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error(`No Segments found in Playlist`);o.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:a,reason:a.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),s){case R.MANIFEST:case R.LEVEL:if(h){if(!l)h=0;else if(l!==o.levels[h]){let e=o.levels.indexOf(l);e>-1&&(h=e)}}o.trigger(L.LEVEL_LOADED,{details:e,levelInfo:l||o.levels[0],level:h||0,id:u||0,stats:n,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:s===R.MANIFEST,context:r});break;case R.AUDIO_TRACK:o.trigger(L.AUDIO_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f,context:r});break;case R.SUBTITLE_TRACK:o.trigger(L.SUBTITLE_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f,context:r})}}},$=class e{static get version(){return Is}static isMSESupported(){return Qf()}static isSupported(){return $f()}static getMediaSource(){return an()}static get Events(){return L}static get MetadataSchema(){return ec}static get ErrorTypes(){return F}static get ErrorDetails(){return I}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:Sm}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Fs,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let n=this.logger=rn(t.debug||!1,`Hls instance`,t.loggerId||t.assetPlayerId),r=this.config=wm(e.DefaultConfig,t,n);this.userConfig=t,r.progressive&&Em(r,n);let{streamController:i,abrController:a,bufferController:o,capLevelController:s,errorController:c,fpsController:l,id3TrackController:u,iframeController:d,gapController:f}=r,p=new c(this),m=this.abrController=new a(this),h=new Ma(this),g=r.interstitialsController,_=g?this.interstitialsController=new g(this,e):null,v=o?this.bufferController=new o(this,h):null,y=s?this.capLevelController=new s(this):null,b=l?new l(this):null,x=r.cmcdController,S=x?this.cmcdController=new x(this):null,C=new Im(this),w=r.contentSteeringController,T=w?new w(this):null,E=this.levelController=new Dm(this,T),D=u?new u(this):void 0,O=new Mm(this.config,this.logger),k=this.streamController=new i(this,h,O),A=this.gapController=f?new f(this,h):void 0;y&&y.setStreamController(k);let j=[C,E,k];_&&j.splice(1,0,_),T&&j.splice(1,0,T),this.networkControllers=j;let M=[m];v&&M.push(v),A&&M.push(A),y&&M.push(y),b&&(b.setStreamController(k),M.push(b)),D&&M.push(D),M.push(h),this.audioTrackController=this.createController(r.audioTrackController,j);let N=r.audioStreamController;N&&j.push(this.audioStreamController=new N(this,h,O)),this.subtitleTrackController=this.createController(r.subtitleTrackController,j);let ee=r.subtitleStreamController;ee&&j.push(this.subtititleStreamController=new ee(this,h,O)),this.createController(r.timelineController,M),O.emeController=this.emeController=this.createController(r.emeController,M),S&&M.push(S),this.latencyController=this.createController(r.latencyController,M),this.coreComponents=M,this.iframeController=d?new d(this,e):void 0,j.push(p);let te=p.onErrorOut;typeof te==`function`&&this.on(L.ERROR,te,p),this.on(L.MANIFEST_LOADED,C.onManifestLoaded,C)}createController(e,t){if(e){let n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error(`An internal error happened while handling event `+e+`. Error message: "`+t.message+`". Here is a stacktrace:`,t),!this.triggeringException){this.triggeringException=!0;let n=e===L.ERROR;this.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:n,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log(`destroy`),this.trigger(L.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0,this.iframeController=void 0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||`media`in e&&!e.media){let t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log(`attachMedia`),this._media&&(this.logger.warn(`media must be detached before attaching`),this.detachMedia());let t=`media`in e,n=t?e.media:e,r=t?e:{media:n};this._media=n,this.trigger(L.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log(`detachMedia`);let e={};this.trigger(L.MEDIA_DETACHING,e),this._media=null,this.trigger(L.MEDIA_DETACHED,e)}transferMedia(){this._media=null;let e=this.bufferController?.transferMedia()||null,t={transferMedia:e};return this.trigger(L.MEDIA_DETACHING,t),this.trigger(L.MEDIA_DETACHED,t),e}loadSource(e){var t;this.stopLoad();let n=this.media,r=this._url,i=this._url=St.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),n&&r&&(r!==i||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(L.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?`, <skip seek to start>`:``)})`),this.started=!0,this.resumeBuffering();for(let n=0;n<this.networkControllers.length&&(this.networkControllers[n].startLoad(e,t),this.started&&this.networkControllers);n++);}stopLoad(){this.logger.log(`stopLoad`),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started&&this.streamController.state!==Q.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log(`resume buffering`),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log(`pause buffering`),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[z.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[z.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[z.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log(`swapAudioCodec`),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log(`recoverMediaError`);let e=this._media,t=this.started,n=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(n?this.startLoad(n):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||=this._sessionId=vn(),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=this.capLevelController,n=!!e;t&&n!==this.config.capLevelToPlayerSize&&(n?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=n)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Ei(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this,r;if(r=t===-1&&e!=null&&e.length?e.length-1:t,n)for(let t=r;t--;){let r=e[t].attrs[`HDCP-LEVEL`];if(r&&r<=n)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){return this.audioStreamController?.getFwdBufferInfo()||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){return this.audioTrackController?.setAudioOption(e)||null}setSubtitleOption(e){return this.subtitleTrackController?.setSubtitleOption(e)||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){return this.audioStreamController?.nextAudioTrack??-1}set nextAudioTrack(e){let{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController?.liveSyncPosition??null}get latency(){return this.latencyController?.latency||0}get maxLatency(){return this.latencyController?.maxLatency||0}get targetLatency(){return this.latencyController?.targetLatency||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){return this.latencyController?.drift||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){return this.levelController.iframeVariants||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){return vi(e,zi(t),navigator.mediaCapabilities)}};$.defaultConfig=void 0;function Lm(){return typeof navigator>`u`||navigator.onLine!==!1}function Rm(){let e=new Set,t=t=>{for(let n of Array.from(e))n(t)},n=()=>t(!0),r=()=>t(!1),i=typeof window<`u`&&typeof window.addEventListener==`function`;return i&&(window.addEventListener(`online`,n),window.addEventListener(`offline`,r)),{isOnline:Lm,onChange(t){return e.add(t),()=>{e.delete(t)}},destroy(){e.clear(),i&&(window.removeEventListener(`online`,n),window.removeEventListener(`offline`,r))}}}var zm={droppedFrames:0};function Bm(e){try{return new URL(e).host}catch{return``}}var Vm=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function Hm(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`||Vm.test(i.name))&&i.startTime>=n){let e=Bm(i.name);e&&(t=e,n=i.startTime)}return t}function Um(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var Wm=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=Um(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)}}},Gm=.25;function Km(e,t){let n=null,r=r=>{n=r===`buffering`?e.currentTime:null,t(r)},i=[[`playing`,()=>r(`playing`)],[`waiting`,()=>r(`buffering`)],[`stalled`,()=>{!e.paused&&e.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&r(`buffering`)}],[`seeked`,()=>{n!==null&&(n=e.currentTime)}],[`timeupdate`,()=>{n!==null&&!e.paused&&!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_FUTURE_DATA&&e.currentTime-n>=Gm&&r(`playing`)}],[`pause`,()=>{e.ended||r(`paused`)}],[`ended`,()=>r(`ended`)]];for(let[t,n]of i)e.addEventListener(t,n);return()=>{for(let[t,n]of i)e.removeEventListener(t,n)}}var qm=2e3,Jm=3,Ym=500,Xm=6e3,Zm=.25,Qm=250,$m=.05,eh=4,th=12e3,nh=.25,rh=1e3;function ih(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 ah(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function oh(){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 sh(){if(typeof navigator>`u`||!oh())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var ch=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 Wm(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:Lm()?new a(`INTERNAL`,0,`native HLS playback error`):new a(`NETWORK`,0,`native HLS playback error while offline`),fatal:!0}),this.onLoaded&&e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=dh(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=ih(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||=Hm(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<=eh,!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=lh();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=qm&&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=lh,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=Ym;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+Zm),s=Math.max(r,t()-n)>=Xm;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,Ym)};this.refocusTimer=setTimeout(i,Ym)}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=uh(e,e.currentTime);t!=null&&((this.lastBufferedEnd==null||Math.abs(t-this.lastBufferedEnd)>=$m)&&(this.bufferedAdvancedAt=lh()),this.lastBufferedEnd=t)},Qm)}checkEndStale(){if(this.endedEmitted)return;let e=lh(),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)>=nh;this.lastSeekableEnd=n;let i=this.deps.video,a=typeof document<`u`&&document.visibilityState===`hidden`;if(r||t>rh||a||i.paused){this.edgeStampedAt=e;return}e-(this.edgeStampedAt??e)>th&&(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=uh(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,(lh()-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-Jm,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 lh(){return typeof performance<`u`?performance.now():Date.now()}function uh(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 dh(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function fh(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 ph=4096;function mh(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>ph))try{return new TextDecoder().decode(n)}catch{return}}var hh=15e3,gh=5e3,_h=6,vh=4e3,yh=2;function bh(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var xh=class{constructor(e={}){i(this,`cmcd`,void 0),i(this,`entries`,new Map),i(this,`keyed`,new Set),i(this,`perTrack`,new Map),i(this,`hints`,new Map),i(this,`stats`,{started:0,served:0,missed:0,failed:0,expired:0,hintStarted:0,hintServed:0,hintFailed:0,hintExpired:0,hintDropped:0}),this.cmcd=e}keyUsable(e){this.keyed.add(e)}isActive(e){return!this.keyed.has(e)}prefetch(e,t,n){if(!this.isActive(t))return;let r=bh(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;i>=_h||(this.perTrack.set(t,i+1),this.start(r,this.withCmcd(e,t,n),!1,hh),this.stats.started+=1)}prefetchHint(e,t){let n=bh(e);if(this.entries.has(n))return;let r=this.hints.get(t)??[];for(;r.length>=yh;){let e=r.shift();e!==void 0&&this.drop(e)&&(this.stats.hintDropped+=1)}r.push(n),this.hints.set(t,r),this.start(n,this.withCmcd(e,t,`media`),!0,vh),this.stats.hintStarted+=1}dropHints(e){for(let t of this.hints.get(e)??[])this.drop(t)&&(this.stats.hintDropped+=1);this.hints.delete(e)}drop(e){let t=this.entries.get(e);return t?(this.entries.delete(e),t.abort.abort(),!0):!1}start(e,t,n,r){let i=new AbortController,a={started:performance.now(),first:0,end:0,hint:n,headers:Promise.resolve(),bytes:Promise.resolve(null),abort:i},o=()=>{};a.headers=new Promise(e=>o=e),a.bytes=fetch(t,{credentials:`omit`,mode:`cors`,signal:i.signal}).then(async e=>{if(a.first=performance.now(),o(),!e.ok)return null;let t=await e.arrayBuffer();return a.end=performance.now(),t}).catch(()=>null).finally(o),this.entries.set(e,a),setTimeout(()=>{this.entries.get(e)===a&&(this.entries.delete(e),i.abort(),n?this.stats.hintExpired+=1:this.stats.expired+=1)},r)}take(e){let t=bh(e),n=this.entries.get(t);return n&&this.entries.delete(t),n}destroy(){for(let e of this.entries.values())e.abort.abort();this.entries.clear(),this.hints.clear()}withCmcd(e,t,n){let{sessionId:r,contentId:i}=this.cmcd;if(!r&&!i)return e;let a=[];i&&a.push(`cid="${i}"`),a.push(`ot=${n===`init`?`i`:t===`audio`?`a`:`v`}`),a.push(`sf=h`),r&&a.push(`sid="${r}"`),a.push(`st=ll`);try{let t=new URL(e);return t.searchParams.set(`CMCD`,a.join(`,`)),t.toString()}catch{return e}}};function Sh(e,t){let n=typeof t==`function`?t:$.DefaultConfig?.loader;if(typeof n!=`function`)return;class r extends n{constructor(...e){super(...e),i(this,`served`,!1),i(this,`cancelled`,!1),i(this,`entry`,void 0),i(this,`stats`,Ch())}load(t,n,r){let i=t.rangeEnd?void 0:e.take(t.url);if(!i){super.load(t,n,r);return}this.served=!0,this.entry=i;let a=performance.now(),o=()=>{i.hint?e.stats.hintFailed+=1:e.stats.failed+=1},s=()=>{!this.cancelled&&this.served&&(i.abort.abort(),o(),this.served=!1,this.entry=void 0,super.load(t,n,r))},c=n?.loadPolicy,l=c?.maxTimeToFirstByteMs||gh,u=setTimeout(s,l);i.headers.then(()=>{clearTimeout(u);let e=c?.maxLoadTimeMs;e&&(u=setTimeout(s,Math.max(0,e-(performance.now()-a))))}),i.bytes.then(s=>{if(clearTimeout(u),this.cancelled||!this.served)return;if(!s){o(),this.served=!1,super.load(t,n,r);return}let c=this.stats;if(i.hint){e.stats.hintServed+=1;let t=performance.now(),n=Math.max(0,(i.end||t)-(i.first||t)),r=Math.max(0,(i.first||t)-a);c.loading.end=t,c.loading.first=t-n,c.loading.start=c.loading.first-r}else e.stats.served+=1,c.loading.start=a,c.loading.first=Math.max(a,i.first||a),c.loading.end=performance.now();c.loaded=c.total=s.byteLength,this.entry=void 0,r.onSuccess({url:t.url,data:s},c,t,null)})}abort(){if(this.served){this.cancelled=!0,this.stats.aborted=!0,this.entry?.abort.abort(),this.entry=void 0;return}super.abort()}}return r}function Ch(){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 wh(e){return e===`audio`?`audio`:`main`}function Th(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 Eh(e){let t=e,n=t?.preloadHint;if(!n||!t?.url||n.TYPE!==`PART`||n[`BYTERANGE-START`]!==void 0||n[`BYTERANGE-LENGTH`]!==void 0)return null;let r=n.URI;if(typeof r!=`string`||!r)return null;try{return new URL(r,t.url).toString()}catch{return null}}function Dh(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}function Oh(){return $.isSupported()}var kh=3,Ah=1e6,jh=20,Mh=1e4,Nh=3,Ph=5,Fh=3,Ih=1e4,Lh=3e4,Rh=12e3,zh=3e3,Bh=.02,Vh=6e3,Hh=.5,Uh=3,Wh=.5,Gh=1.1,Kh=.25,qh=5e3,Jh=4e3,Yh=2,Xh=5,Zh=2,Qh=2,$h=4,eg=4,tg=2e3,ng=3e4,rg=1,ig=2,ag=.5,og=.6,sg=2,cg=1.5,lg=1e4,ug=18e4,dg=.5,fg=2;function pg(e){let t=e.config??{};return t.capLevelToPlayerSize===!0||t.capLevelOnFPSDrop===!0}var mg=8,hg=12e4,gg=6e4;function _g(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}function vg(){return typeof self<`u`&&self.devicePixelRatio>0?self.devicePixelRatio:1}var yg=.2,bg=30,xg=2,Sg=2,Cg=2,wg=9,Tg=.5,Eg=64,Dg=1e4,Og=8,kg=.6,Ag=.4,jg=.4,Mg=2,Ng=6e4,Pg=.5,Fg=3.5,Ig=300;function Lg(e){return(e?.part??e?.frag)?.stats}function Rg(){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 zg(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Cg;let t=Math.max(12,e.liveSyncDuration+wg);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),Bg(e,e.liveSyncDuration)}function Bg(e,t){let n=(e,t,n)=>Math.min(n,Math.max(t,e));e.maxStarvationDelay??=n(t/2,.5,4),e.maxLoadingDelay??=n(t,1,4),e.abrEwmaFastLive??=n(t/2,1,3)}var Vg=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,`offlineHold`,!1),i(this,`onOffline`,null),i(this,`onOnline`,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,`headroomSamples`,[]),i(this,`headroomGranted`,!1),i(this,`lastStallAt`,0),i(this,`headroomRegrantAt`,0),i(this,`headroomUngated`,!1),i(this,`playingSince`,0),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,`stallCapBitrate`,null),i(this,`stallCapSince`,0),i(this,`stallCapTickAt`,0),i(this,`stallDownCaps`,0),i(this,`stallCapEnabled`,void 0),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.stallCapEnabled=e.stallCap!==!1,this.frameCounter=new Wm(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=ah(n)&&oh(),o=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!o){r({type:`error`,error:new a(`DRM_CLIENT`,0,e.drm?.fairplay?.licenseUrl&&i?`FairPlay cannot be played on the hls.js engine (WebKit binds keys via the media sinf box); use engine "auto" or "native"`:`DRM is required but none of the stream’s key systems is usable on this platform (WebKit takes FairPlay only; other browsers take Widevine only)`),fatal:!0});return}e.drmEnabled&&o&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&(Xe(n),rt()),this.startHls(),t!==!1&&typeof document<`u`&&(this.onVisibility=()=>{let e=this.hls;if(document.visibilityState!==`visible`||!e)return;let t=e.liveSyncPosition;if(typeof t!=`number`)return;let r=typeof e.targetLatency==`number`&&e.targetLatency>0?e.targetLatency:3;t-n.currentTime>Math.max(r*3,8)&&(n.currentTime=t)},document.addEventListener(`visibilitychange`,this.onVisibility)),typeof window<`u`&&(this.onOffline=()=>{this.offlineHold=!0,this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),this.lastAdvanceMs=this.lastAdvanceMs?Date.now():0,this.resetStarvationWindow(),this.clearKick()},this.onOnline=()=>{if(this.offlineHold&&(this.offlineHold=!1,this.networkRecoveries=0,this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),!this.stopped&&this.hls&&this.loadStarted&&!this.loadSuspended)){this.lastAdvanceMs=Date.now(),this.lastFragLoadingMs=0,this.resetStarvationWindow(),this.resetChaseWindow(),this.clearKick();try{this.hls.startLoad(-1)}catch{}}},window.addEventListener(`offline`,this.onOffline),window.addEventListener(`online`,this.onOnline),Lm()||this.onOffline()),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}},qh))}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=vg(),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+Tg||(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)<Bh)){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=ah(this.deps.video)&&oh(),d={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,liveDurationInfinity:!0,maxBufferHole:.5,maxLiveSyncPlaybackRate:u?1:1.1,abrEwmaDefaultEstimate:this.startEstimate(),capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...l?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:Ye.video,audioRobustness:Ye.audio,videoEncryptionScheme:Ye.scheme,audioEncryptionScheme:Ye.scheme},...We()?{requestMediaKeySystemAccessFunc:Je(e)}:{},licenseXhrSetup:(e,a)=>{let o=performance.now(),s=()=>{e.open(`POST`,this.licenseUrl??a,!0),e.setRequestHeader(`x-api-key`,n.apiKey),e.setRequestHeader(`X-Match-Urn`,t.matchUrn),e.setRequestHeader(`X-Device-Id`,r),i&&e.setRequestHeader(`X-User-Id`,i),this.licenseRequested=!0,e.addEventListener(`loadend`,()=>{this.licenseTimeMs===0&&(this.licenseTimeMs=Math.max(1,Math.round(performance.now()-o)))})},{freshLicenseUrl:c}=this.deps;if(!c||!fh(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),Ih)});return Promise.race([c().catch(()=>void 0),d]).finally(()=>clearTimeout(u)).then(e=>{if(!this.hls||this.hls!==l)throw Error(`havik-player: engine torn down during refresh`);e&&(this.licenseUrl=e),s()})}}:{},...t.analytics?.sid?{cmcd:{sessionId:t.analytics.sid,contentId:t.matchUrn,useHeaders:!1}}:{},...s};this.prefetch?.destroy(),this.prefetch=null;let f=!1,p=!1,m=l&&this.deps.mediaDuringKey!==!1,h=this.deps.preloadHints!==!1;if((m||h)&&!d.fLoader){let e=new xh({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=Sh(e,d.loader);n&&(this.prefetch=e,f=m,p=h,d.fLoader=n)}zg(d),this.catchUpRate=typeof d.maxLiveSyncPlaybackRate==`number`?d.maxLiveSyncPlaybackRate:1,this.catchUpEngaged=!1,this.catchUpRate>1&&(d.maxLiveSyncPlaybackRate=1),this.sizeCapManaged=d.capLevelToPlayerSize!==!0,this.fpsCapManaged=!(s&&`capLevelOnFPSDrop`in s),this.loadStarted=d.autoStartLoad!==!1;let g=new $(d);if(this.hls=g,this.armHoldBack(g,d),g.on($.Events.FRAG_PARSED,(e,t)=>this.reanchorPartTimeline(g,t)),g.on($.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,l&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&this.dropLevelsWidevineCannotPlay(g),this.measureLadder(g),this.applySizeCap(),this.loadSuspended=!1,e.paused&&this.schedulePauseSuspend(),c({type:`ready`})}),g.on($.Events.FRAG_BUFFERED,(e,t)=>{t?.frag?.type===`main`&&(this.kickKind!==`dead`&&this.clearKick(),(this.mediaRecoveries>0||this.networkRecoveries>0||this.licenseRecoveries>0||this.starvationKicks>0||this.starvationRebuilds>0)&&!this.recoveryResetTimer&&(this.recoveryResetTimer=setTimeout(()=>{this.mediaRecoveries=0,this.networkRecoveries=0,this.licenseRecoveries=0,this.starvationKicks=0,this.starvationRebuilds=0,this.recoveryResetTimer=null},Lh)))}),g.on($.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),g.on($.Events.FRAG_LOADED,(e,t)=>{t?.frag?.type===`main`&&(this.mainFragsSinceTick+=1,this.bwFragsLoaded+=1,this.maybeRememberBandwidth(!1));let n=t?.frag,r=Lg(t),i=r?.loaded;typeof i==`number`&&(this.bytesLoaded+=i),!this.reportedFirstBytes&&typeof i==`number`&&i>0&&(this.reportedFirstBytes=!0,c({type:`firstBytes`}));let a=r?.loading;a&&a.end>0&&a.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(a.end-a.start))),this.requestTimesMs.length>Eg&&this.requestTimesMs.shift()),this.sampleHoldBack(t),this.sampleHeadroom(t);let o=n?.url;if(o){let e=Bm(o);e&&(this.cdnHost=e)}}),g.on($.Events.LEVEL_LOADED,(e,t)=>{let n=t?.stats?.loaded;if(typeof n==`number`&&(this.playlistBytesLoaded+=n),this.reportedFirstPlaylist||(this.reportedFirstPlaylist=!0,c({type:`firstPlaylist`})),this.detectedLowLatency)return;let r=t.details;r?.partList?.length||(r?.partTarget??0)>0?(this.detectedLowLatency=!0,c({type:`lowLatencyDetected`,value:!0}),this.headroomUngated&&(this.headroomUngated=!1,this.applySizeCapUnlessPending())):r&&!this.headroomUngated&&(this.headroomUngated=!0,this.applySizeCapUnlessPending())}),g.on($.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.prefetch&&p){let e=this.prefetch,t=this.deps.video,n=(n,r)=>{if(t.paused)return;let i=n;if(!i?.live||!i.partList?.length||typeof i.edge!=`number`)return;let a=t.buffered,o=a.length?a.end(a.length-1):0;if(i.edge-o>kh*(i.partTarget||.5))return;let s=Eh(n);s&&e.prefetchHint(s,r)};g.on($.Events.LEVEL_LOADED,(e,t)=>{t.level===g.loadLevel&&n(t.details,`main`)}),g.on($.Events.AUDIO_TRACK_LOADED,(e,t)=>{t?.id===g.audioTrack&&n(t?.details,`audio`)}),g.on($.Events.LEVEL_SWITCHING,()=>e.dropHints(`main`)),g.on($.Events.AUDIO_TRACK_SWITCHING,()=>e.dropHints(`audio`))}if(this.prefetch&&f){let e=this.prefetch;g.on($.Events.KEY_LOADING,(t,n)=>{let r=n?.frag,i=wh(r?.type);if(r&&e.isActive(i))for(let t of Th(g,r))e.prefetch(t.url,i,t.kind)}),g.on($.Events.KEY_LOADED,(t,n)=>e.keyUsable(wh(n?.frag?.type)))}g.on($.Events.KEY_LOADED,()=>{l&&!this.reportedDrmReady&&(this.reportedDrmReady=!0,c({type:`drmReady`}))}),this.endWatchdog&&clearInterval(this.endWatchdog),this.endWatchdog=setInterval(()=>{this.checkEndStale(),this.checkStarvation(),this.updateCatchUpBand(),this.checkFutileChase(),this.adaptHoldBack(),this.reviewSizeCapHeadroom(),this.releaseStallCap(),this.checkFrameDrops()},zh),g.on($.Events.LEVEL_SWITCHED,(e,t)=>{this.renditionSwitches+=1;let n=this.lastLevelIndex>=0?g.levels[this.lastLevelIndex]:void 0,r=g.levels[t.level];n&&r&&r.bitrate!==n.bitrate&&(r.bitrate>n.bitrate?this.upshifts+=1:this.downshifts+=1),this.lastLevelIndex=t.level,this.armFrameDropGrace(),c({type:`qualitychange`,index:t.level})}),g.on($.Events.AUDIO_TRACK_SWITCHED,(e,t)=>c({type:`audiotrackchange`,id:t.id})),g.on($.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>c({type:`texttrackchange`,id:t.id})),g.on($.Events.ERROR,(e,t)=>this.onError(t)),g.loadSource(t.manifestUrl),g.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(t){if(e==null)this.bitrateCapLevel=-1;else{let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),this.bitrateCapLevel=n}this.pushCap()}}sizeCapCover(){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=vg(),s=a.ignoreDevicePixelRatio?1:o;return s=Math.min(s,a.maxDevicePixelRatio??1/0),{cover:Ll.getMaxLevelByMediaSize(e.levels,r*s,i*s),deviceRatio:o}}sizeCapCoverLevel(){return this.sizeCapCover()?.cover??null}computeSizeCapTarget(){let e=this.hls,t=this.sizeCapCover();if(!e||!t)return null;let{cover:n,deviceRatio:r}=t,i=this.deps.sizeCapHeadroom,a=i==null||Number.isNaN(i);if(a&&r>=ig)return n;if(a)return this.headroomUngated||this.headroomGranted?_g(e.levels,n,rg):n;let o=i===1/0?e.levels.length:Math.max(0,Math.floor(i));return _g(e.levels,n,o)}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?tg:ng;this.capTimer=setTimeout(()=>{this.capTimer=null;let n=this.computeSizeCapTarget();n===e||t===ng&&n!=null&&n<e?this.applySizeCap():this.onMediaResize()},t)}measureLadder(e){let t=e.levels.map(e=>e.height).filter(e=>!!e);this.ladderHeights=t.length?[...new Set(t)].sort((e,t)=>e-t):void 0,this.ladderTopBitrateKbps=e.levels.length?Math.round(Math.max(...e.levels.map(e=>e.bitrate))/1e3):0}dropLevelsWidevineCannotPlay(e){this.removeLevelsWhere(e,e=>it(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&Ze(e)!==`avc`&&!!Ze(e)));for(let n of t)nt(n).then(t=>{t||this.hls!==e||this.removeLevelsWhere(e,e=>e===n)&&(this.measureLadder(e),this.applySizeCap())})}removeLevelsWhere(e,t){let n=e.levels??[],r=[],i=new Set;if(n.forEach((e,n)=>{let a=e.videoCodec;a&&Ze(a)&&t(a)&&(r.push(n),i.add(a))}),!r.length)return!1;let a=[...i].join(`, `);if(!n.some((e,t)=>r.includes(t)?!1:!Ze(e.videoCodec)||it(e.videoCodec)===!0))return console.warn(`havik-player: every rendition is ${a}, which Widevine may not play on this browser; keeping them`),!1;for(let t=r.length-1;t>=0;--t)e.removeLevel(r[t]);return console.info(`havik-player: skipped ${r.length} rendition(s) Widevine cannot play on this browser (${a})`),!0}defaultHeadroomApplies(){let e=this.deps.sizeCapHeadroom;return e!=null&&!Number.isNaN(e)||this.headroomUngated?!1:vg()<ig}applySizeCapUnlessPending(){this.capTimer||this.applySizeCap()}sampleHeadroom(e){if(!this.sizeCapManaged||!this.defaultHeadroomApplies()||e.frag?.type!==`main`||typeof e.frag.level!=`number`||typeof document<`u`&&document.hidden)return;let t=e.part?e.part.duration:this.detectedLowLatency?0:e.frag.duration;if(typeof t!=`number`||!(t>0))return;let n=Lg(e)?.loading;if(!n||!(n.start>0)||!(n.end>=n.start))return;let r=this.hls?.levels?.[e.frag.level]?.bitrate;if(!(typeof r==`number`&&r>0))return;let i=(n.end-n.start)/(t*1e3);this.headroomSamples.push({t:Date.now(),ratio:i,bitrate:r}),this.headroomSamples.length>256&&this.headroomSamples.shift()}onPlaybackStall(e){let t=Date.now();this.deps.video.seeking||!this.playingSince||t-this.playingSince<lg||(this.lastStallAt=t,this.stepStallCapDown(t,e),this.headroomGranted&&(this.headroomGranted=!1,this.applySizeCapUnlessPending()))}stallCapLevel(e){if(this.stallCapBitrate==null)return-1;let t=-1;return e.levels.forEach((e,n)=>{e.bitrate<=this.stallCapBitrate&&(t=n)}),t<0?0:t}stepStallCapDown(e,t){let n=this.hls;if(!n||!this.stallCapEnabled||pg(n)||!n.autoLevelEnabled||typeof t==`number`&&t>=dg||this.isLiveEdgeWait(n,t??0))return;this.stallCapBitrate!=null&&(this.stallCapSince=e);let r=Math.max(n.levels[n.currentLevel]?.bitrate??0,n.levels[n.loadLevel]?.bitrate??0);if(!(r>0))return;let i=n.levels.map(e=>e.bitrate).filter(e=>e>0&&e<r).sort((e,t)=>t-e)[0];i!=null&&(this.stallCapBitrate!=null&&i>=this.stallCapBitrate||(this.stallCapBitrate=i,this.stallCapSince=e,this.stallDownCaps+=1,this.pushCap()))}isLiveEdgeWait(e,t){let n=e.latestLevelDetails;if(!n?.live)return!1;let r=n.partTarget||n.targetduration;return!(r>0)||!(n.edge>0)?!1:n.edge-(this.deps.video.currentTime+t)<fg*r}releaseStallCap(){let e=this.hls,t=Date.now(),n=this.stallCapTickAt;if(this.stallCapTickAt=t,!e||this.stallCapBitrate==null)return;if(this.deps.video.paused||this.loadSuspended||this.offlineHold){n&&(this.stallCapSince+=t-Math.max(n,this.stallCapSince));return}if(t-this.stallCapSince<ug)return;let r=this.stallCapBitrate,i=e.levels.map(e=>e.bitrate).filter(e=>e>r).sort((e,t)=>e-t)[0];this.stallCapBitrate=i??null,this.stallCapSince=t,this.pushCap()}reviewSizeCapHeadroom(){let e=Date.now(),{video:t}=this.deps;!t.paused&&!t.seeking&&t.readyState>=3?this.playingSince||=e:this.playingSince=0;let n=this.hls;if(!n||!this.sizeCapManaged)return;if(!this.defaultHeadroomApplies()){this.headroomGranted=!1,this.headroomSamples=[];return}this.headroomSamples=this.headroomSamples.filter(t=>t.t>=e-Dg);let r=this.headroomEarned(n,e);r!==this.headroomGranted&&(r||(this.headroomRegrantAt=e+gg),this.headroomGranted=r,this.applySizeCapUnlessPending())}headroomEarned(e,t){if(t-this.lastStallAt<hg||!this.headroomGranted&&t<this.headroomRegrantAt||!this.headroomGranted&&this.headroomSamples.length<mg)return!1;let n=e.levels,r=this.sizeCapCoverLevel();if(r==null)return this.headroomGranted;let i=_g(n,r,rg);if(i===r)return this.headroomGranted;let a=n[i]?.bitrate,o=e.bandwidthEstimate,s=this.headroomGranted?cg:sg;if(!(a>0)||!(o>=s*a))return!1;let c=e=>Dh([...e].sort((e,t)=>e-t),90);if(this.headroomGranted){let e=this.headroomSamples.filter(e=>e.bitrate>=a).map(e=>e.ratio);return e.length<mg||c(e)<=og}let l=[];for(let e of this.headroomSamples)e.bitrate<a&&l.push(e.ratio*(a/e.bitrate));return l.length>=mg&&c(l)<=ag}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)],[`stall`,this.stallCapLevel(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,stallDownCaps:this.stallDownCaps,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;i&&i.height>0&&(n.maxLevelHeight=i.height,!pg(e)&&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.offlineHold||!Lm()){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>Vh&&this.suspendChasing(),e>Rh&&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.offlineHold||!Lm()){this.resetStarvationWindow();return}let n=Date.now(),r=this.lastAdvanceMs!==0&&n-this.lastAdvanceMs<Vh,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>Jh,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=Um(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>$h&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=Zh&&(this.clearKick(),this.starvationRebuilds<Qh)){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>=Yh,d=!i&&this.deadTicks>=$h&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=eg;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=Xh))){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||this.offlineHold)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>Hh?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=Hh&&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=Sg,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||this.offlineHold||t.paused||!e.autoLevelEnabled||typeof document<`u`&&document.hidden){this.resetFrameDropWindow();return}let{totalFrames:n,dropped:r}=Um(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<bg||o<0){this.fpsBadTicks=0;return}if(this.fpsGraceTicks>0){--this.fpsGraceTicks,this.fpsBadTicks=0;return}if(o<=yg*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<xg)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||this.offlineHold||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(Gh,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=Wh){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<Uh)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+Kh||(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.headroomSamples=[],this.headroomGranted=!1,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=Rg();if(!(n>=Ig))return;let r=typeof t==`number`&&t>0?t:this.holdBackBase,i=Math.min(this.holdBackCeiling(e),this.holdBackBase+Pg);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:Fg,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=Lg(e)?.loading;if(!r||!(r.start>0)||!(r.end>0))return;let i=r.first>r.start?r.first:r.end,a=Math.max(0,i-r.start)/(n*1e3);this.holdBackSamples.push({t:Date.now(),ratio:a}),this.holdBackSamples.length>256&&this.holdBackSamples.shift()}adaptHoldBack(){if(!this.holdBackEnabled)return;let e=this.hls;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||this.offlineHold||typeof document<`u`&&document.hidden){this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[];return}let t=Date.now(),n=t-Dg,r=this.holdBackSamples,i=0;for(;i<r.length&&r[i].t<n;)i+=1;i>0&&r.splice(0,i);let a=e.targetLatency;if(typeof a!=`number`||!(a>0))return;this.holdBackBase<0&&(this.holdBackBase=a);let o=this.holdBackBase,s=this.holdBackCeiling(e);if(r.length<Og){this.holdBackSlowTicks=0;return}let c=r.map(e=>e.ratio).sort((e,t)=>e-t),l=Dh(c,95),u=Dh(c,50),d=Math.round(l*1e3);if(l>=kg&&u>=Ag){if(this.holdBackFastSince=0,this.holdBackSlowTicks+=1,this.holdBackSlowTicks<Mg)return;this.holdBackSlowTicks=0;let t=Math.ceil((s-o)/Pg),n=Math.ceil((a-o)/Pg-1e-9);if(n>this.holdBackStepCount&&(this.holdBackStepCount=n),this.holdBackStepCount>=t)return;this.holdBackStepCount+=1;let r=Math.min(s,o+this.holdBackStepCount*Pg);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>=jg){this.holdBackFastSince=0;return}if(this.holdBackFastSince===0){this.holdBackFastSince=t;return}if(t-this.holdBackFastSince<Ng||(this.holdBackFastSince=t,this.holdBackStepCount===0||a!==this.holdBackApplied))return;--this.holdBackStepCount;let f=Math.max(o,o+this.holdBackStepCount*Pg);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?Ah:ze()??Ah}maybeRememberBandwidth(e){if(this.deps.rememberBandwidth===!1||this.bwFragsLoaded<jh)return;let t=Date.now();if(!e&&t-this.bwSavedAt<Mh)return;let n=this.hls?.bandwidthEstimate;typeof n!=`number`||!Number.isFinite(n)||n<=0||(this.bwSavedAt=t,Be(n))}destroy(){if(this.maybeRememberBandwidth(!0),this.detachFrames?.(),this.detachFrames=null,this.prefetch?.destroy(),this.prefetch=null,this.clearRecoveryReset(),this.capTimer&&=(clearTimeout(this.capTimer),null),this.capObserver&&=(this.capObserver.disconnect(),null),this.unwatchDprChanges(),this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onOffline&&typeof window<`u`&&(window.removeEventListener(`offline`,this.onOffline),this.onOffline=null),this.onOnline&&typeof window<`u`&&(window.removeEventListener(`online`,this.onOnline),this.onOnline=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>=Fh)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.details===$.ErrorDetails.BUFFER_STALLED_ERROR&&this.onPlaybackStall(e.buffer),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(!Lm()&&(e.response?.code??0)===0){this.offlineHold=!0,this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null);return}if(this.networkRecoveries<Ph){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<Nh){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(mh(e.networkDetails)):void 0;return new a(t===`DRM`?c(n,o):t===`NETWORK`&&n===0?`NETWORK`:n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`,o?{serverCode:o}:void 0)}},Hg=15e3,Ug=6e5,Wg=3e5,Gg=100,Kg=1,qg=1e3,Jg=3e4,Yg=1e3,Xg={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},Zg={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`},Qg=new Set([`INVALID_URN`,`NOT_FOUND`,`GEO_DENIED`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),$g={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 e_(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 t_=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),n_=new Set,r_=new Set,i_=new Set,a_=e=>`this page's Content-Security-Policy blocks QoE beacons. Add ${e} to connect-src; until then none are sent.`;function o_(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(n_.has(t)&&!r_.has(t)){r_.add(t),b(a_(new URL(t).origin));for(let e of i_)e.noteCspBlocked()}}function s_(e,t){return b(t,e),{disabledReason:t}}function c_(e,t,n){if(n)return t&&!t_(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return s_(`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=e_(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return s_(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 l_=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??Hg,idleMs:e.idleMs??Ug},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(),qg),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&&n_.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,o_),i_.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,Wg);return this.lastTickMs>0&&e-this.lastTickMs>=t?(this.endIdle(this.lastTickMs),!0):(this.lastTickMs=e,!1)}syncIdle(e){e===`paused`&&this.opts.idleMs?this.idleTimer===null&&(this.idleTimer=setTimeout(()=>{this.idleTimer=null,this.endIdle()},this.opts.idleMs)):this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}endIdle(e){this.endedFlag||(this.end(`END_REASON_IDLE`,e),this.opts.onIdle?.())}noteStateChange(e,t,n,r){if(this.endedFlag||e===t)return;let i=this.now();if(t===`playing`?(this.playingSinceMs===null&&(this.playingSinceMs=i),this.startupTimeMs===0&&(this.startupTimeMs=Math.max(Kg,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(Kg,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(Kg,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:$g[e]??`PLAYER_STATE_UNSPECIFIED`,toState:$g[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:Xg[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<Yg}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(Kg,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=Kg),this.firstPlaylistMs>0&&(this.firstPlaylistMs=Kg),this.firstFragLoadMs>0&&(this.firstFragLoadMs=Kg),this.drmSetupMs>0&&(this.drmSetupMs=Kg))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(Kg,this.now()-this.startupAnchorMs))}noteFirstPlaylist(){this.firstPlaylistMs===0&&(this.firstPlaylistMs=Math.max(Kg,this.now()-this.startupAnchorMs))}noteDrmReady(){this.drmSetupMs===0&&(this.drmSetupMs=Math.max(Kg,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(Kg,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(Qg.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=$g[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=Dh(n,50),o.requestTimeP95Ms=Dh(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=Zg[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,i_.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<=Jg&&(i.abandonAfterStallMs=Math.max(Kg,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=Jg&&(i.abandonAfterErrorMs=Math.max(Kg,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?.(a_(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&r_.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>Gg;){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 u_(){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 d_(){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 f_(){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 p_(e){let t=u_(),n={deviceClass:d_(),integration:t.integration,...f_()};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 m_(){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 h_=`2.27.1`,g_={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`},__={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 v_(e,t){let n={...g_,...t};for(let t of Object.keys(__))e.style.setProperty(__[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var y_=`havik-player-styles`,b_=`
|
|
46
|
+
`)),n}getTextAndFormat(){return this.rows}},$p=class{constructor(e,t,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Qp(n),this.nonDisplayedMemory=new Qp(n),this.lastOutputScreen=new Qp(n),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>`MODE=`+e),this.mode===`MODE_POP-ON`?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!==`MODE_ROLL-UP`&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?`DISP`:`NON_DISP`;this.logger.log(2,()=>t+`: `+this.writeScreen.getDisplayText(!0)),(this.mode===`MODE_PAINT-ON`||this.mode===`MODE_ROLL-UP`)&&(this.logger.log(1,()=>`DISPLAYED: `+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,`RCL - Resume Caption Loading`),this.setMode(`MODE_POP-ON`)}ccBS(){this.logger.log(2,`BS - BackSpace`),this.mode!==`MODE_TEXT`&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,`DER- Delete to End of Row`),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,`RU(`+e+`) - Roll Up`),this.writeScreen=this.displayedMemory,this.setMode(`MODE_ROLL-UP`),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,`FON - Flash On`),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,`RDC - Resume Direct Captioning`),this.setMode(`MODE_PAINT-ON`)}ccTR(){this.logger.log(2,`TR`),this.setMode(`MODE_TEXT`)}ccRTD(){this.logger.log(2,`RTD`),this.setMode(`MODE_TEXT`)}ccEDM(){this.logger.log(2,`EDM - Erase Displayed Memory`),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,`CR - Carriage Return`),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,`ENM - Erase Non-displayed Memory`),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,`EOC - End Of Caption`),this.mode===`MODE_POP-ON`){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>`DISP: `+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,`TO(`+e+`) - Tab Offset`),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};t.underline=e%2==1,t.italics=e>=46,t.foreground=t.italics?`white`:[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`][Math.floor(e/2)-16],this.logger.log(2,`MIDROW: `+q(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},em=class{constructor(e,t,n){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=rm(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Kp,this.field=e,this.outputFilters=[null,t,n]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var n;this.outputFilters[e]=t,(n=this.channels[e])==null||n.setHandler(t)}getChannel(e){let t=this.channels[e];return t||=this.channels[e]=new $p(this.field+e-1,this.outputFilters[e],this.logger),t}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){let n=t[e]&127,r=t[e+1]&127,i=!1,a=null;if(n===0&&r===0)continue;this.logger.log(3,()=>`[`+qp([t[e],t[e+1]])+`] -> (`+qp([n,r])+`)`);let o=this.cmdHistory;if(n>=16&&n<=31){if(nm(n,r,o)){tm(null,null,o),this.logger.log(3,()=>`Repeated command (`+qp([n,r])+`) is dropped`);continue}tm(n,r,this.cmdHistory),i=this.parseCmd(n,r),i||=this.parseMidrow(n,r),i||=this.parsePAC(n,r),i||=this.parseBackgroundAttributes(n,r)}else tm(null,null,o);if(!i&&(a=this.parseChars(n,r),a)){let e=this.currentChannel;e&&e>0?this.getChannel(e).insertChars(a):this.logger.log(2,`No channel found yet. TEXT-MODE?`)}!i&&!a&&this.logger.log(2,()=>`Couldn't parse cleaned data `+qp([n,r])+` orig: `+qp([t[e],t[e+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;let n=e===20||e===21||e===23?1:2,r=this.getChannel(n);return e===20||e===21||e===28||e===29?t===32?r.ccRCL():t===33?r.ccBS():t===34?r.ccAOF():t===35?r.ccAON():t===36?r.ccDER():t===37?r.ccRU(2):t===38?r.ccRU(3):t===39?r.ccRU(4):t===40?r.ccFON():t===41?r.ccRDC():t===42?r.ccTR():t===43?r.ccRTD():t===44?r.ccEDM():t===45?r.ccCR():t===46?r.ccENM():t===47&&r.ccEOC():r.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(n=e===17?1:2,n!==this.currentChannel)return this.logger.log(0,`Mismatch channel in midrow parsing`),!1;let r=this.channels[n];return r?(r.ccMIDROW(t),this.logger.log(3,()=>`MIDROW (`+qp([e,t])+`)`),!0):!1}return!1}parsePAC(e,t){let n;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;let r=e<=23?1:2;return n=t>=64&&t<=95?r===1?Vp[e]:Up[e]:r===1?Hp[e]:Wp[e],this.getChannel(r).setPAC(this.interpretPAC(n,t)),this.currentChannel=r,!0}interpretPAC(e,t){let n,r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=(n&1)==1,n<=13?r.color=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`white`][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color=`white`):r.indent=Math.floor((n-16)/2)*4,r}parseChars(e,t){let n,r=null,i=null;if(e>=25?(n=2,i=e-8):(n=1,i=e),i>=17&&i<=19){let e;e=i===17?t+80:i===18?t+112:t+144,this.logger.log(2,()=>`Special char '`+Rp(e)+`' in channel `+n),r=[e]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>`Char codes = `+qp(r).join(`,`)),r}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let n,r={};e===16||e===24?(n=Math.floor((t-32)/2),r.background=Gp[n],t%2==1&&(r.background+=`_semi`)):t===45?r.background=`transparent`:(r.foreground=`black`,t===47&&(r.underline=!0));let i=e<=23?1:2;return this.getChannel(i).setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}tm(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let n=this.channels[t];n&&n.cueSplitAtTime(e)}}};function tm(e,t,n){n.a=e,n.b=t}function nm(e,t,n){return n.a===e&&n.b===t}function rm(){return{a:null,b:null}}var im=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},am=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=sm(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(L.FRAG_LOADING,this.onFragLoading,this),e.on(L.FRAG_LOADED,this.onFragLoaded,this),e.on(L.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(L.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(L.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(L.FRAG_LOADING,this.onFragLoading,this),e.off(L.FRAG_LOADED,this.onFragLoaded,this),e.off(L.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(L.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(L.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new im(this,`textTrack1`),t=new im(this,`textTrack2`),n=new im(this,`textTrack3`),r=new im(this,`textTrack4`);this.cea608Parser1=new em(1,e,t),this.cea608Parser2=new em(3,n,r)}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=om(r[0],r[1],t,n);if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),a=!0,o/(n-t)>.5))return}if(a||i.push([t,n]),this.config.renderTextTracksNatively){let i=this.cueCache[e];if(i){let e=this.Cues.newCue(null,t,n,r);e.length&&i.push.apply(i,e)}else{let i=this.captionsTracks[e].track;this.Cues.newCue(i,t,n,r)}}else{let i=this.Cues.newCue(null,t,n,r),a=this.captionsProperties[e]?.media;this.hls.trigger(L.CUES_PARSED,{type:`captions`,cues:i,track:e,closedCaptions:a})}}onInitPtsFound(e,{id:t,timestampOffsets:n}){let{unparsedFrags:r}=this;t===z.MAIN&&(this.initPTS=n),r.length&&(this.unparsedFrags=[],r.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(L.FRAG_LOADED,e):this.hls.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:Error(`Subtitle discontinuity domain does not match main`)})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:n,cueCache:r,media:i}=this,{label:a,languageCode:o}=t[e];i&&(r[e]=[],n[e]=Mf(i,`captions`,a,o,`hidden`))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let n={_id:e,label:t.label,kind:`captions`,default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(L.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let n=!!t.transferMedia;if(this.media=null,!n){if(this.config.renderTextTracksNatively){let{captionsTracks:e,cueCache:t}=this;for(let n in e)e[n].remove(),delete t[n]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=sm(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let n=t.subtitleTracks||[];if(n.length&&!this.config.renderTextTracksNatively&&!Pl(this.tracks,n)){let e=n.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(L.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}this.tracks=n}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){return this.hls.levels[e.level]?.attrs[`CLOSED-CAPTIONS`]}onFragLoading(e,t){if(this.enabled&&t.frag.type===z.MAIN){let{cea608Parser1:e,cea608Parser2:n,lastSn:r}=this,{cc:i,sn:a}=t.frag,o=t.part?.index??-1;e&&n&&(a!==r+1||a===r&&o!==this.lastPartIndex+1||i!==this.lastCc)&&(e.reset(),n.reset()),this.lastCc=i,this.lastSn=a,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:n,payload:r}=t;if(n.level<this.tracks.length&&n.type===z.SUBTITLE){var i;if(r.byteLength||(i=n.initSegment)!=null&&(i=i.data)!=null&&i.byteLength){let e=n.decryptdata,r=`stats`in t;if(e==null||!e.encrypted||r){let e=this.tracks[n.level],r=this.vttCCs;r[n.cc]||(r[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e?.textCodec===gf?this._parseIMSC1(t):this._parseVTTs(t)}}else{let e=`part`in t?t.part:null;this.hls.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:e,error:Error(`Empty subtitle payload`)})}}}_parseIMSC1(e){let{frag:t,payload:n}=e,r=`part`in e?e.part:null;if(!this.initPTS[t.cc]){this.unparsedFrags.push(e);return}let i=this.hls;bf(n,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),i.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},e=>{i.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${e}`),i.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:e})})}_parseVTTs(e){let{frag:t,payload:n}=e,r=`part`in e?e.part:null,{initPTS:i,unparsedFrags:a}=this,o=i.length-1;if(!i[t.cc]&&o===-1){a.push(e);return}let s=this.hls,c=t.initSegment?.data;hf(c?Tr(c,new Uint8Array(n)).buffer:n,this.initPTS[t.cc],this.vttCCs,t.cc,(r&&!c?r:t).start,e=>{this._appendCues(e,t.level),s.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},n=>{let i=n.message.startsWith(`Missing initPTS`);if(s.logger.log(`${i?`Deferred parsing of`:`Cannot parse`} VTT cue (sn: ${t.sn} @${t.start}): ${n}`),i){a.push(e);return}this.config.enableIMSC1&&this._fallbackToIMSC1(e),s.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:n})})}_fallbackToIMSC1(e){let{frag:t,payload:n}=e,r=this.tracks[t.level];r.textCodec||bf(n,this.initPTS[t.cc],()=>{r.textCodec=gf,this._parseIMSC1(e)},()=>{r.textCodec=`wvtt`})}_appendCues(e,t){let n=this.hls;if(this.config.renderTextTracksNatively){let n=this.tracks[t].trackNode?.track;if(!n||n.mode===`disabled`)return;e.forEach(e=>Pf(n,e))}else{let r=this.tracks[t];if(!r)return;let i=r.default?`default`:`subtitles`+t;n.trigger(L.CUES_PARSED,{type:`subtitles`,cues:e,track:i,subtitleTrack:r})}}onFragDecrypted(e,t){let{frag:n}=t;n.type===z.SUBTITLE&&this.onFragLoaded(L.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:n,samples:r}=t;if(n.type!==z.MAIN||this.closedCaptionsForLevel(n)!==`NONE`)for(let e=0;e<r.length;e++){let t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();let n=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,n[0]),this.cea608Parser2.addData(r[e].pts,n[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var n;let{type:e,timeRanges:r}=t;if(e===`video`&&(n=r[e])!=null&&n.length){let{captionsTracks:e,cueCache:t}=this;Object.keys(t).forEach(n=>{let r=e[n]?.track;if(r){let e=t[n];for(let t=0;t<e.length;t++)Pf(r,e[t])}delete t[n]})}}}onBufferFlushing(e,t){let{startOffset:n,endOffset:r,endOffsetSubtitles:i,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<r)){if(!a||a===`video`){let{captionsTracks:e,cueCache:t}=this;Object.keys(e).forEach(t=>Ff(e[t].track,n,r)),Object.keys(t).forEach(e=>{let i=t[e];for(let e=i.length;e--;){let t=i[e];t.startTime>=n&&t.endTime<=r&&i.splice(e,1)}})}this.config.renderTextTracksNatively&&n===0&&i!==void 0&&this.tracks.forEach(e=>{let t=e.trackNode?.track;t&&Ff(t,n,i)})}}extractCea608Data(e){let t=[[],[]],n=e[0]&31,r=2;for(let i=0;i<n;i++){let n=e[r++],i=127&e[r++],a=127&e[r++];if((i!==0||a!==0)&&4&n){let e=3&n;(e===0||e===1)&&(t[e].push(i),t[e].push(a))}}return t}};function om(e,t,n,r){return Math.min(t,r)-Math.max(e,n)}function sm(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var cm=/\s/,lm={newCue(e,t,n,r){let i=[],a,o,s,c,l,u=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(a=r.rows[f],s=!0,c=0,l=``,!a.isEmpty()){var d;for(let e=0;e<a.chars.length;e++)cm.test(a.chars[e].uchar)&&s?c++:(l+=a.chars[e].uchar,s=!1);a.cueStartTime=t,t===n&&(n+=1e-4),c>=16?c--:c++;let r=lf(l.trim()),p=mf(t,n,r);e!=null&&(d=e.cues)!=null&&d.getCueById(p)||(o=new u(t,n,r),o.id=p,o.line=f+1,o.align=`left`,o.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(o))}return e&&i.length&&(i.sort((e,t)=>e.line===`auto`||t.line===`auto`?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>Pf(e,t))),i}},um=class{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new Ct}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,n){let r=this.stats;if(r.loading.start)throw Error(`Loader can only be used once.`);r.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Wt(e,t,!0))this.retry(e);else{U.warn(`timeout while loading ${this.context?.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:n}=this;this.retryDelay=Ht(e,n.retry),n.retry++,U.warn(`${status?`HTTP Status `+status:`Timeout`} while loading ${t?.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function dm(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var fm=/(\d+)-(\d+)\/(\d+)/,pm=class extends um{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||_m}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){let{config:e,context:t,stats:n}=this;if(!e||!t)return;n.loading.first=0,n.loaded=0,n.aborted=!1,this.controller=new self.AbortController;let r=mm(t,this.controller.signal),i=t.responseType===`arraybuffer`,a=i?`byteLength`:`length`,{maxTimeToFirstByteMs:o,maxLoadTimeMs:s}=e.loadPolicy;this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&P(o)?o:s,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(El(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{this.response=r;let a=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=s,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},s-(a-n.loading.start)),!r.ok){let{status:e,statusText:t}=r;throw new vm(t||`fetch, bad network response`,e,r)}n.loading.first=a,n.total=gm(r.headers)||n.total;let o=this.callbacks?.onProgress;return o&&P(e.highWaterMark)?this.loadProgressively(r,n,t,e.highWaterMark,o):i?r.arrayBuffer():t.responseType===`json`?r.json():r.text()}).then(r=>{var i;let o=this.response;if(!o)throw Error(`loader destroyed`);self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);let s=r[a];s&&(n.loaded=n.total=s);let c={url:o.url,data:r,code:o.status},l=this.callbacks?.onProgress;l&&!P(e.highWaterMark)&&l(n,t,r,o),(i=this.callbacks)==null||i.onSuccess(c,n,t,o)}).catch(r=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;let i=r&&r.code||0,a=r?r.message:null,o=e.loadPolicy.errorRetry,s=n.retry;if(Wt(o,s,!1,{url:t.url,data:void 0,code:i}))this.retry(o);else{var c;U.error(`${i} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:i,text:a},t,r?r.details:null,n)}})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,n,r=0,i){let a=new As,o=e.body.getReader(),s=()=>o.read().then(o=>{if(o.done)return a.dataLength&&i(t,n,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=o.value,l=c.length;return t.loaded+=l,l<r||a.dataLength?(a.push(c),a.dataLength>=r&&i(t,n,a.flush().buffer,e)):i(t,n,c.buffer,e),s()}).catch(()=>Promise.reject());return s()}};function mm(e,t){let n={method:`GET`,mode:`cors`,credentials:`same-origin`,signal:t,headers:new self.Headers(V({},e.headers))};return e.rangeEnd&&n.headers.set(`Range`,`bytes=`+e.rangeStart+`-`+String(e.rangeEnd-1)),n}function hm(e){let t=fm.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function gm(e){let t=e.get(`Content-Range`);if(t){let e=hm(t);if(P(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function _m(e,t){return new self.Request(e.url,t)}var vm=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},ym=(e,t,n)=>Math.max(t,Math.min(e,n)),bm=/^age:\s*[\d.]+\s*$/im,xm=class extends um{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return i.call(this,n,t.url,t)}).catch(e=>{if(!(this.loader!==n||this.stats.aborted))return n.open(`GET`,t.url,!0),i.call(this,n,t.url,t)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,t,e)}).catch(e=>{var i;(i=this.callbacks)==null||i.onError({code:n.status,text:e.message},t,n,r)}):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open(`GET`,t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=n.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader(`Range`,`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&P(i)?i:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:n}=this;if(!e||!t)return;let r=t.readyState,i=this.config;if(!n.aborted&&r>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,s=t.responseType===`text`?t.responseText:null;if(r>=200&&r<300){let i=s??t.response;if(i!=null){var a;n.loading.end=Math.max(self.performance.now(),n.loading.first);let o=t.responseType===`arraybuffer`?i.byteLength:i.length;n.loaded=n.total=o,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);let s=this.callbacks?.onProgress;s&&s(n,e,i,t);let c={url:t.responseURL,data:i,code:r};e.rangeEnd&&o!==e.rangeEnd-e.rangeStart&&U.warn(`Payload length ${o} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(a=this.callbacks)==null||a.onSuccess(c,n,e,t);return}}let c=i.loadPolicy.errorRetry,l=n.retry;if(Wt(c,l,!1,{url:e.url,data:void 0,code:r}))this.retry(c);else{var o;U.error(`${r} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:r,text:t.statusText},e,t,n)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&bm.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,`im`).test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},Sm=H(H({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:`edge`,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:xm,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:`process`,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Oo,requireKeySystemAccessOnStart:!1,reuseKeySessions:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:rp,abrController:Qi,bufferController:wa,capLevelController:Ll,errorController:ua,fpsController:$d,id3TrackController:Xf,gapController:Vf,latencyController:Mp},Cm()),{},{subtitleStreamController:Fp,subtitleTrackController:Rf,timelineController:am,audioStreamController:Ml,audioTrackController:Il,emeController:qd,cmcdController:Bd,contentSteeringController:Hd,iframeController:dp,interstitialsController:jp});function Cm(){return{cueHandler:lm,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:`English`,captionsTextTrack1LanguageCode:`en`,captionsTextTrack2Label:`Spanish`,captionsTextTrack2LanguageCode:`es`,captionsTextTrack3Label:`Unknown CC`,captionsTextTrack3LanguageCode:``,captionsTextTrack4Label:`Unknown CC`,captionsTextTrack4LanguageCode:``,renderTextTracksNatively:!0}}function wm(e,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error(`Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration`);if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error(`Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"`);if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error(`Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"`);if(t.liveMaxUnchangedPlaylistRefresh!==void 0){let e=t.liveMaxUnchangedPlaylistRefresh,r=ym(e,2,1/0);r!==e&&n.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${e} to ${r}.`),t.liveMaxUnchangedPlaylistRefresh=r}let r=Tm(e),i=[`manifest`,`level`,`frag`],a=[`TimeOut`,`MaxRetry`,`RetryDelay`,`MaxRetryTimeout`];return i.forEach(e=>{let i=`${e===`level`?`playlist`:e}LoadPolicy`,o=t[i]===void 0,s=[];a.forEach(n=>{let a=`${e}Loading${n}`,c=t[a];if(c!==void 0&&o){s.push(a);let e=r[i].default;switch(t[i]={default:e},n){case`TimeOut`:e.maxLoadTimeMs=c,e.maxTimeToFirstByteMs=c;break;case`MaxRetry`:e.errorRetry.maxNumRetry=c,e.timeoutRetry.maxNumRetry=c;break;case`RetryDelay`:e.errorRetry.retryDelayMs=c,e.timeoutRetry.retryDelayMs=c;break;case`MaxRetryTimeout`:e.errorRetry.maxRetryDelayMs=c,e.timeoutRetry.maxRetryDelayMs=c}}}),s.length&&n.warn(`hls.js config: "${s.join(`", "`)}" setting(s) are deprecated, use "${i}": ${q(t[i])}`)}),H(H({},r),t)}function Tm(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(Tm):Object.keys(e).reduce((t,n)=>(t[n]=Tm(e[n]),t),{}):e}function Em(e,t){let n=e.loader;n!==pm&&n!==xm?(t.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):dm()&&(e.loader=pm,e.progressive=!0,e.enableSoftwareAES=!0,t.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var Dm=class extends Nl{constructor(e,t){super(e,`level-controller`),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this),e.on(L.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this),e.off(L.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let n=this.hls.config.preferManagedMediaSource,r=[],i={},a={},o=!1,s=!1,c=!1,l=!1;t.levels.forEach(e=>{let t=e.attrs,u=Am(e,n),{audioCodec:d,videoCodec:f,imageCodec:p,width:m,height:h}=e;if(!u){this.log(`Some or all CODECS not supported "${t.CODECS}"`);return}o||=!!(m&&h),s||=!!f,c||=!!d,l||=!!p;let{CODECS:g,"FRAME-RATE":_,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:b,"VIDEO-RANGE":x}=t,S=`${`${y||`.`}-`}${e.bitrate}-${b}-${_}-${g}-${x}-${v}`;if(!i[S]){let t=this.createLevel(e);i[S]=t,a[S]=1,r.push(t)}else if(i[S].uri!==e.url&&!e.attrs[`PATHWAY-ID`]){let t=a[S]+=1;e.attrs[`PATHWAY-ID`]=Array(t+1).join(`.`);let n=this.createLevel(e);i[S]=n,r.push(n)}else e.iframes||(i[S].addGroupId(`audio`,t.AUDIO),i[S].addGroupId(`text`,t.SUBTITLES))}),this.filterAndSortMediaOptions(r,t,o,s,c,l)}createLevel(e){let t=new Mi(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!km(n.videoCodec,this.hls.config.preferManagedMediaSource)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(e.message),t.supportedResult=gi(e,[])}return t}filterAndSortMediaOptions(e,t,n,r,i,a){let o=[],s=[],c=e,l=t.stats?.parsing||{},u=this.hls.config.preferManagedMediaSource;if((n||r)&&i&&(c=c.filter(({videoCodec:e,videoRange:t,width:n,height:r})=>(!!e||!!(n&&r))&&Oi(t))),r&&a&&(c=c.filter(e=>!e.imageCodec)),c.length===0){Promise.resolve().then(()=>{if(this.hls){let e=`no level with compatible codecs found in manifest`,n=e;t.levels.length&&(n=`one or more CODECS in variant not supported: ${q(t.levels.map(e=>e.attrs.CODECS).filter((e,t,n)=>n.indexOf(e)===t))}`,this.warn(n),e+=` (${n})`);let r=Error(e);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:n})}}),l.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(e=>!e.audioCodec||Om(e.audioCodec,u)),jm(o)),t.subtitles&&(s=t.subtitles,jm(s));let d=c.slice(0);c.sort((e,t)=>{if(e.attrs[`HDCP-LEVEL`]!==t.attrs[`HDCP-LEVEL`])return(e.attrs[`HDCP-LEVEL`]||``)>(t.attrs[`HDCP-LEVEL`]||``)?1:-1;if(n&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Di.indexOf(e.videoRange)-Di.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let n=ei(e.videoCodec),r=ei(t.videoCodec);if(n!==r)return r-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let n=ti(e.codecSet),r=ti(t.codecSet);if(n!==r)return r-n}return e.averageBitrate===t.averageBitrate?0:e.averageBitrate-t.averageBitrate});let f=d[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==d.length)){for(let e=0;e<d.length;e++)if(d[e].pathwayId===c[0].pathwayId){f=d[e];break}}this._levels=c;for(let e=0;e<c.length;e++)if(c[e]===f){this._firstLevel=e;let t=f.bitrate,n=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${t}`),this.hls.userConfig?.abrEwmaDefaultEstimate===void 0){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>n&&n===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let p=t.iframeVariants.filter(e=>Am(e,u));this._iframeVariants=p;let m=i&&!r,h=this.hls.config,g=!!(h.audioStreamController&&h.audioTrackController),_={levels:c,audioTracks:o,subtitleTracks:s,iframeVariants:p,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:r,altAudio:g&&!m&&o.some(e=>!!e.url)};l.end=performance.now(),this.hls.trigger(L.MANIFEST_PARSED,_)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let n=Error(`invalid level idx`),r=e<0;if(this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}let n=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs[`PATHWAY-ID`]:void 0,a=t[e],o=a.attrs[`PATHWAY-ID`];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&r&&i===o)return;this.log(`Switching to level ${e} (${a.height?a.height+`p `:``}${a.videoRange?a.videoRange+` `:``}${a.codecSet?a.codecSet+` `:``}@${a.bitrate})${o?` with Pathway `+o:``} from level ${n}${i?` with Pathway `+i:``}`);let s={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(L.LEVEL_SWITCHING,s);let c=a.details;if(!c||c.live){let e=this.switchParams(a.uri,r?.details,c);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e===void 0?this.hls.firstAutoLevel:e}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),n=e.filter(e=>t.indexOf(e)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=n}}onError(e,t){!t.fatal&&t.context&&t.context.type===R.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===z.MAIN){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var n;let{level:r,details:i}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let e=a.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else(n=t.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,i=e.attrs[`PATHWAY-ID`],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${i?` Pathway `+i:``}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${n}`),this.hls.trigger(L.LEVEL_LOADING,{url:n,level:r,levelInfo:e,pathwayId:e.attrs[`PATHWAY-ID`],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex===-1?this.hls.nextAutoLevel:this.manualLevelIndex}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let n=this.hls.config.abrSwitchInterval;if(n>0){let r=performance.now(),i=r-this.lastABRSwitchTime,a=n*1e3;if(this.lastABRSwitchTime>-1&&i<a){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(i)}ms < ${a}ms / ${n}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(i)}ms >= ${a}ms / ${n}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let n=this._levels.filter((t,n)=>n!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));_s(n),this._levels=n,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=n.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&=Math.min(this._startLevel,r),this.hls.trigger(L.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(L.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}};function Om(e,t){return Zr(e,`audio`,t)}function km(e,t){return Zr(e,`video`,t)}function Am(e,t){let{audioCodec:n,videoCodec:r}=e;n&&(e.audioCodec=n=ai(n,t)||void 0),r&&=e.videoCodec=li(r);let{unknownCodecs:i}=e;return!(i?.length||n&&!Om(n,t)||r&&!km(r,t))}function jm(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}var Mm=class extends Xt{constructor(e,t){super(`key-loader`,t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let t in this.keyLoaderInfo){let n=this.keyLoaderInfo[t].loader;if(n){if(e&&e!==n.context?.frag.type)return;n.abort()}}}destroy(){for(let e in this.keyLoaderInfo){let t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,n){return this.emeController?this.emeController.loadClear(e,t,n):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(n=>this.loadInternal(e,t,n)):this.loadInternal(e,t)}loadInternal(e,t,n){n&&e.setKeyFormat(n);let r=e.decryptdata;if(!r){let t=Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,t))}let i=e;switch(r.method){case`SAMPLE-AES`:case`SAMPLE-AES-CENC`:case`SAMPLE-AES-CTR`:return r.keyFormat===`identity`?this.loadKeyHTTP(i):t?t.then(()=>this.loadKeyEME(i)):this.loadKeyEME(i);case`AES-128`:case`AES-256`:case`AES-256-CTR`:return this.loadKeyHTTP(i);default:return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let t=hr(e.initSegment.data);if(t.length){let n=t[0],r=e.decryptdata.uri;if(n.some(e=>e!==0))this.log(`Using keyId found in init segment ${Hn(n)} keyUri: ${r}`),Po.setKeyIdForUri(r,n);else{let e=Po.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Hn(e)} keyUri: ${r}`),n=e}e.decryptdata.keyId=n}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,n=t.uri;if(!n)return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,Error(`Invalid key URI: "${n}"`)));let r=this.keyLoaderInfo[n];if(r){if(r.decryptdata.key)return t.key=r.decryptdata.key,r.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:r});if(r.keyLoadPromise)return r.keyLoadPromise.then(n=>(t.key=r.decryptdata.key,H(H({},n),{},{frag:e})))}this.log(`Loading${t.keyId?` keyId: `+Hn(t.keyId):``} URI: ${t.uri} from ${e.type} ${e.level}`);let i=this.config,a=i.loader,o=new a(i);e.keyLoader=o;let s=this.keyLoaderInfo[n]={decryptdata:t,keyLoadPromise:null,loader:o};return s.keyLoadPromise=new Promise((t,r)=>{let a={type:R.KEY,keyInfo:s,frag:e,responseType:`arraybuffer`,url:n},c=i.keyLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};o.load(a,l,{onSuccess:(e,n,i,a)=>{let{frag:o,keyInfo:s,url:c}=i;if(!o.decryptdata||s!==this.keyLoaderInfo[c])return this.resetLoader(i),r(Nm(o,I.KEY_LOAD_ERROR,Error(`after key load, decryptdata unset or changed`),a));s.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=s.loader=s.keyLoadPromise=null,t({frag:o,keyInfo:s})},onError:(t,i,a,o)=>{this.resetLoader(i),r(Nm(e,I.KEY_LOAD_ERROR,Error(`HTTP Error ${t.code} loading key ${t.text}`),a,H({url:n,data:void 0},t)))},onTimeout:(t,n,i)=>{this.resetLoader(n),r(Nm(e,I.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),i))},onAbort:(t,n,i)=>{this.resetLoader(n),r(Nm(e,I.INTERNAL_ABORTED,Error(`key loading aborted`),i))}})})}resetLoader(e){let{frag:t,keyInfo:n,url:r}=e,i=n.loader;t.keyLoader===i&&(t.keyLoader=n.loader=n.keyLoadPromise=null),delete this.keyLoaderInfo[r],i&&i.destroy()}};function Nm(e,t=I.KEY_LOAD_ERROR,n,r,i){return new Xa({type:F.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r||null})}function Pm(e){let{type:t}=e;switch(t){case R.AUDIO_TRACK:return z.AUDIO;case R.SUBTITLE_TRACK:return z.SUBTITLE;default:return z.MAIN}}function Fm(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var Im=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(L.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_LOADING,this.onLevelLoading,this),e.off(L.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(L.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,n=t.pLoader,r=t.loader,i=new(n||r)(t);return this.loaders[e.type]=i,i}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:`text`,type:R.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:n,level:r,pathwayId:i,url:a,deliveryDirectives:o,levelInfo:s}=t;this.load({id:n,level:r,pathwayId:i,responseType:`text`,type:R.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:s})}onAudioTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:R.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:R.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let n=this.loaders[R.LEVEL];if(n){let e=n.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(n.abort(),delete this.loaders[R.LEVEL])}}load(e){let t=this.hls.config,n=this.getInternalLoader(e);if(n){let t=this.hls.logger,r=n.context;if(r?.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives)){r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`);return}t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(r=e.type===R.MANIFEST?t.manifestLoadPolicy.default:V({},t.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),P(e.deliveryDirectives?.part)){let t;if(e.type===R.LEVEL&&e.level!==null?t=this.hls.levels[e.level].details:e.type===R.AUDIO_TRACK&&e.id!==null?t=this.hls.audioTracks[e.id].details:e.type===R.SUBTITLE_TRACK&&e.id!==null&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,n=t.targetduration;if(e&&n){let t=Math.max(e*3,n*.8)*1e3;r=V({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}let i=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0};n.load(e,a,{onSuccess:(e,t,n,r)=>{let i=this.getInternalLoader(n);this.resetInternalLoader(n.type);let a=e.data;t.parsing.start=performance.now(),Uo.isMediaPlaylist(a)||n.type!==R.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,n,r||null,i):this.handleMasterPlaylist(e,t,n,r)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}})}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?`auto`:`force`} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,n,r){let i=this.hls,a=e.data,o=Fm(e,n),s=Uo.parseMasterPlaylist(a,o);if(s.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,n,s.playlistParsingError,r,t);return}let{contentSteering:c,levels:l,iframeVariants:u,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m}=s;this.variableList=m,l.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:n}=this.hls.config,{audioCodec:r,videoCodec:i}=e;for(let a=t.length;a--;){let o=t[a];Zr(o,`audio`,n)?(e.audioCodec=r=r?`${r},${o}`:o,Yr.audio[r.substring(0,4)]=2,t.splice(a,1)):Zr(o,`video`,n)&&(e.videoCodec=i=i?`${i},${o}`:o,Yr.video[i.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:h=[],SUBTITLES:g,"CLOSED-CAPTIONS":_}=Uo.parseMasterPlaylistMedia(a,o,s);h.length&&!h.some(e=>!e.url)&&l[0].audioCodec&&!l[0].attrs.AUDIO&&(this.hls.logger.log(`[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one`),h.unshift({type:`main`,name:`main`,groupId:`main`,default:!1,autoselect:!1,forced:!1,id:-1,attrs:new so({}),bitrate:0,url:``})),i.trigger(L.MANIFEST_LOADED,{levels:l,audioTracks:h,subtitles:g,iframeVariants:u,captions:_,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m})}handleTrackOrLevelPlaylist(e,t,n,r,i){let a=this.hls,{id:o,level:s,type:c}=n,l=Fm(e,n),u=P(s)?s:P(o)?o:0,d=Pm(n),f=Uo.parseLevelPlaylist(e.data,l,u,d,0,this.variableList);if(c===R.MANIFEST){let e={attrs:new so({}),bitrate:0,details:f,name:``,url:l};f.requestScheduled=t.loading.start+ps(f,0),a.trigger(L.MANIFEST_LOADED,{levels:[e],audioTracks:[],iframeVariants:[],url:l,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,i)}handleManifestParsingError(e,t,n,r,i){this.hls.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.MANIFEST_PARSING_ERROR,fatal:t.type===R.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,n=!1,r,i){let a=`A network ${n?`timeout`:`error`+(r?` (status `+r.code+`)`:``)} occurred while loading ${e.type}`;e.type===R.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===R.AUDIO_TRACK||e.type===R.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let s=I.UNKNOWN,c=!1,l=this.getInternalLoader(e);switch(e.type){case R.MANIFEST:s=n?I.MANIFEST_LOAD_TIMEOUT:I.MANIFEST_LOAD_ERROR,c=!0;break;case R.LEVEL:s=n?I.LEVEL_LOAD_TIMEOUT:I.LEVEL_LOAD_ERROR,c=!1;break;case R.AUDIO_TRACK:s=n?I.AUDIO_TRACK_LOAD_TIMEOUT:I.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case R.SUBTITLE_TRACK:s=n?I.SUBTITLE_TRACK_LOAD_TIMEOUT:I.SUBTITLE_LOAD_ERROR,c=!1}l&&this.resetInternalLoader(e.type);let u={type:F.NETWORK_ERROR,details:s,fatal:c,url:e.url,loader:l,context:e,error:o,networkDetails:t,stats:i};if(r){let n=e.url;t&&`url`in t&&(n=t.url),u.response=H({url:n,data:void 0},r)}this.hls.trigger(L.ERROR,u)}handlePlaylistLoaded(e,t,n,r,i,a){let o=this.hls,{type:s,level:c,levelOrTrack:l,id:u,groupId:d,deliveryDirectives:f}=r,p=Fm(t,r),m=Pm(r),h=typeof r.level==`number`&&m===z.MAIN?c:void 0;l&&`iframes`in l&&l.iframes&&!e.iframesOnly&&(e.playlistParsingError=Error(`EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag`),e.iframesOnly=!0);let g=e.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:g,reason:g.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error(`No Segments found in Playlist`);o.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:a,reason:a.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),s){case R.MANIFEST:case R.LEVEL:if(h){if(!l)h=0;else if(l!==o.levels[h]){let e=o.levels.indexOf(l);e>-1&&(h=e)}}o.trigger(L.LEVEL_LOADED,{details:e,levelInfo:l||o.levels[0],level:h||0,id:u||0,stats:n,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:s===R.MANIFEST,context:r});break;case R.AUDIO_TRACK:o.trigger(L.AUDIO_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f,context:r});break;case R.SUBTITLE_TRACK:o.trigger(L.SUBTITLE_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f,context:r})}}},$=class e{static get version(){return Is}static isMSESupported(){return Qf()}static isSupported(){return $f()}static getMediaSource(){return an()}static get Events(){return L}static get MetadataSchema(){return ec}static get ErrorTypes(){return F}static get ErrorDetails(){return I}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:Sm}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Fs,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let n=this.logger=rn(t.debug||!1,`Hls instance`,t.loggerId||t.assetPlayerId),r=this.config=wm(e.DefaultConfig,t,n);this.userConfig=t,r.progressive&&Em(r,n);let{streamController:i,abrController:a,bufferController:o,capLevelController:s,errorController:c,fpsController:l,id3TrackController:u,iframeController:d,gapController:f}=r,p=new c(this),m=this.abrController=new a(this),h=new Ma(this),g=r.interstitialsController,_=g?this.interstitialsController=new g(this,e):null,v=o?this.bufferController=new o(this,h):null,y=s?this.capLevelController=new s(this):null,b=l?new l(this):null,x=r.cmcdController,S=x?this.cmcdController=new x(this):null,C=new Im(this),w=r.contentSteeringController,T=w?new w(this):null,E=this.levelController=new Dm(this,T),D=u?new u(this):void 0,O=new Mm(this.config,this.logger),k=this.streamController=new i(this,h,O),A=this.gapController=f?new f(this,h):void 0;y&&y.setStreamController(k);let j=[C,E,k];_&&j.splice(1,0,_),T&&j.splice(1,0,T),this.networkControllers=j;let M=[m];v&&M.push(v),A&&M.push(A),y&&M.push(y),b&&(b.setStreamController(k),M.push(b)),D&&M.push(D),M.push(h),this.audioTrackController=this.createController(r.audioTrackController,j);let N=r.audioStreamController;N&&j.push(this.audioStreamController=new N(this,h,O)),this.subtitleTrackController=this.createController(r.subtitleTrackController,j);let ee=r.subtitleStreamController;ee&&j.push(this.subtititleStreamController=new ee(this,h,O)),this.createController(r.timelineController,M),O.emeController=this.emeController=this.createController(r.emeController,M),S&&M.push(S),this.latencyController=this.createController(r.latencyController,M),this.coreComponents=M,this.iframeController=d?new d(this,e):void 0,j.push(p);let te=p.onErrorOut;typeof te==`function`&&this.on(L.ERROR,te,p),this.on(L.MANIFEST_LOADED,C.onManifestLoaded,C)}createController(e,t){if(e){let n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error(`An internal error happened while handling event `+e+`. Error message: "`+t.message+`". Here is a stacktrace:`,t),!this.triggeringException){this.triggeringException=!0;let n=e===L.ERROR;this.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:n,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log(`destroy`),this.trigger(L.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0,this.iframeController=void 0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||`media`in e&&!e.media){let t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log(`attachMedia`),this._media&&(this.logger.warn(`media must be detached before attaching`),this.detachMedia());let t=`media`in e,n=t?e.media:e,r=t?e:{media:n};this._media=n,this.trigger(L.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log(`detachMedia`);let e={};this.trigger(L.MEDIA_DETACHING,e),this._media=null,this.trigger(L.MEDIA_DETACHED,e)}transferMedia(){this._media=null;let e=this.bufferController?.transferMedia()||null,t={transferMedia:e};return this.trigger(L.MEDIA_DETACHING,t),this.trigger(L.MEDIA_DETACHED,t),e}loadSource(e){var t;this.stopLoad();let n=this.media,r=this._url,i=this._url=St.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),n&&r&&(r!==i||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(L.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?`, <skip seek to start>`:``)})`),this.started=!0,this.resumeBuffering();for(let n=0;n<this.networkControllers.length&&(this.networkControllers[n].startLoad(e,t),this.started&&this.networkControllers);n++);}stopLoad(){this.logger.log(`stopLoad`),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started&&this.streamController.state!==Q.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log(`resume buffering`),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log(`pause buffering`),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[z.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[z.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[z.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log(`swapAudioCodec`),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log(`recoverMediaError`);let e=this._media,t=this.started,n=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(n?this.startLoad(n):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||=this._sessionId=vn(),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=this.capLevelController,n=!!e;t&&n!==this.config.capLevelToPlayerSize&&(n?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=n)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Ei(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this,r;if(r=t===-1&&e!=null&&e.length?e.length-1:t,n)for(let t=r;t--;){let r=e[t].attrs[`HDCP-LEVEL`];if(r&&r<=n)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){return this.audioStreamController?.getFwdBufferInfo()||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){return this.audioTrackController?.setAudioOption(e)||null}setSubtitleOption(e){return this.subtitleTrackController?.setSubtitleOption(e)||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){return this.audioStreamController?.nextAudioTrack??-1}set nextAudioTrack(e){let{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController?.liveSyncPosition??null}get latency(){return this.latencyController?.latency||0}get maxLatency(){return this.latencyController?.maxLatency||0}get targetLatency(){return this.latencyController?.targetLatency||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){return this.latencyController?.drift||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){return this.levelController.iframeVariants||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){return vi(e,zi(t),navigator.mediaCapabilities)}};$.defaultConfig=void 0;function Lm(){return typeof navigator>`u`||navigator.onLine!==!1}function Rm(){let e=new Set,t=t=>{for(let n of Array.from(e))n(t)},n=()=>t(!0),r=()=>t(!1),i=typeof window<`u`&&typeof window.addEventListener==`function`;return i&&(window.addEventListener(`online`,n),window.addEventListener(`offline`,r)),{isOnline:Lm,onChange(t){return e.add(t),()=>{e.delete(t)}},destroy(){e.clear(),i&&(window.removeEventListener(`online`,n),window.removeEventListener(`offline`,r))}}}var zm={droppedFrames:0};function Bm(e){try{return new URL(e).host}catch{return``}}var Vm=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function Hm(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`||Vm.test(i.name))&&i.startTime>=n){let e=Bm(i.name);e&&(t=e,n=i.startTime)}return t}function Um(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var Wm=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=Um(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)}}},Gm=.25,Km=1e3;function qm(e,t){let n=null,r=r=>{n=r===`buffering`?e.currentTime:null,t(r)},i=()=>typeof performance<`u`?performance.now():Date.now(),a=i(),o=e.currentTime,s=()=>{let t=e.currentTime;t>o&&!e.seeking&&!e.paused&&(a=i()),o=t},c=[[`playing`,()=>{a=i(),o=e.currentTime,r(`playing`)}],[`waiting`,()=>r(`buffering`)],[`stalled`,()=>{if(e.paused)return;let t=e.readyState<HTMLMediaElement.HAVE_FUTURE_DATA,n=i()-a>=Km;(t||n)&&r(`buffering`)}],[`seeked`,()=>{o=e.currentTime,n!==null&&(n=e.currentTime)}],[`timeupdate`,()=>{s(),n!==null&&!e.paused&&!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_FUTURE_DATA&&e.currentTime-n>=Gm&&r(`playing`)}],[`pause`,()=>{e.ended||r(`paused`)}],[`ended`,()=>r(`ended`)]];for(let[t,n]of c)e.addEventListener(t,n);return()=>{for(let[t,n]of c)e.removeEventListener(t,n)}}var Jm=2e3,Ym=3,Xm=500,Zm=6e3,Qm=.25,$m=250,eh=.05,th=4,nh=12e3,rh=.25,ih=1e3,ah=8e3,oh=.05,sh=2,ch=3e4;function lh(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 uh(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function dh(){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 fh(){if(typeof navigator>`u`||!dh())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var ph=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,`lastPlayhead`,null),i(this,`playheadStampedAt`,null),i(this,`movingSince`,null),i(this,`stuckReloads`,0),i(this,`stuckReloadsTotal`,0),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 Wm(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:Lm()?new a(`INTERNAL`,0,`native HLS playback error`):new a(`NETWORK`,0,`native HLS playback error while offline`),fatal:!0}),this.onLoaded&&e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=gh(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=lh(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||=Hm(this.builtAt),this.cdnHost&&(n.cdnHost=this.cdnHost),this.deps.descriptor.drmEnabled&&(n.keySystem=`fairplay`),n.stuckReloads=this.stuckReloadsTotal,e.duration===1/0){n.isLive=!0;let t=this.liveEdgeEstimate(),r=t==null?NaN:t-e.currentTime;Number.isFinite(r)&&(n.atLiveEdge=r<=th,!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=mh();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=Jm&&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=mh,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=Xm;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+Qm),s=Math.max(r,t()-n)>=Zm;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,Xm)};this.refocusTimer=setTimeout(i,Xm)}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,this.resetStuck(),e.type===`emptied`&&this.resetEndStale()},e.addEventListener(`seeking`,this.onEdgeReset),e.addEventListener(`emptied`,this.onEdgeReset),this.edgeTimer=setInterval(()=>{if(e.duration!==1/0)return;let t=mh(),n=this.lastTickAt==null?0:t-this.lastTickAt;this.lastTickAt=t;let r=hh(e,e.currentTime);r!=null&&((this.lastBufferedEnd==null||Math.abs(r-this.lastBufferedEnd)>=eh)&&(this.bufferedAdvancedAt=t),this.lastBufferedEnd=r),this.checkEndStale(t,n),this.checkStuck(t,n)},$m)}checkEndStale(e,t){if(this.endedEmitted)return;let n=this.liveEnd();if(n==null)return;let r=this.lastSeekableEnd==null||Math.abs(n-this.lastSeekableEnd)>=rh;this.lastSeekableEnd=n;let i=this.deps.video,a=typeof document<`u`&&document.visibilityState===`hidden`;if(r||t>ih||a||i.paused){this.edgeStampedAt=e;return}e-(this.edgeStampedAt??e)>nh&&(this.endedEmitted=!0,this.deps.emit({type:`ended`,reason:`stalled`}))}resetEndStale(){this.lastSeekableEnd=null,this.edgeStampedAt=null,this.lastTickAt=null}checkStuck(e,t){if(this.deps.stuckReload===!1||this.endedEmitted)return;let n=this.deps.video,r=n.currentTime,i=this.lastPlayhead==null||!Number.isFinite(r)||Math.abs(r-this.lastPlayhead)>=oh;this.lastPlayhead=Number.isFinite(r)?r:null;let a=typeof document<`u`&&document.visibilityState===`hidden`,o=t>ih||a||n.paused||n.seeking||n.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||!Lm();if(i||o){this.playheadStampedAt=e,i&&!o?(this.movingSince??=e,this.stuckReloads>0&&e-this.movingSince>=ch&&(this.stuckReloads=0)):this.movingSince=null;return}this.movingSince=null;let s=e-(this.playheadStampedAt??e),c=this.bufferedAdvancedAt==null?1/0:e-this.bufferedAdvancedAt;s<=ah||c<=ah||(this.playheadStampedAt=e,!(this.stuckReloads>=sh)&&this.reloadStuck())}resetStuck(){this.lastPlayhead=null,this.playheadStampedAt=null,this.movingSince=null}reloadStuck(){let{video:e,descriptor:t}=this.deps;this.stuckReloads+=1,this.stuckReloadsTotal+=1;let n=!e.paused;console.warn(`havik-player: native playback frozen, buffer not growing: reloading at live`);try{e.src=gh(t.manifestUrl,t.analytics?.sid),e.load()}catch(e){console.warn(`havik-player: reload failed`,e);return}n&&Promise.resolve(e.play()).catch(e=>{console.warn(`havik-player: play() after the reload was refused`,e)})}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.resetStuck(),this.lastBufferedEnd=null,this.bufferedAdvancedAt=null}liveEdgeEstimate(){let e=this.deps.video;if(e.duration!==1/0)return null;let t=this.liveEnd(),n=hh(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,(mh()-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-Ym,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 mh(){return typeof performance<`u`?performance.now():Date.now()}function hh(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 gh(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function _h(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 vh=4096;function yh(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>vh))try{return new TextDecoder().decode(n)}catch{return}}var bh=15e3,xh=5e3,Sh=6,Ch=4e3,wh=2;function Th(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var Eh=class{constructor(e={}){i(this,`cmcd`,void 0),i(this,`entries`,new Map),i(this,`keyed`,new Set),i(this,`perTrack`,new Map),i(this,`hints`,new Map),i(this,`stats`,{started:0,served:0,missed:0,failed:0,expired:0,hintStarted:0,hintServed:0,hintFailed:0,hintExpired:0,hintDropped:0}),this.cmcd=e}keyUsable(e){this.keyed.add(e)}isActive(e){return!this.keyed.has(e)}prefetch(e,t,n){if(!this.isActive(t))return;let r=Th(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;i>=Sh||(this.perTrack.set(t,i+1),this.start(r,this.withCmcd(e,t,n),!1,bh),this.stats.started+=1)}prefetchHint(e,t){let n=Th(e);if(this.entries.has(n))return;let r=this.hints.get(t)??[];for(;r.length>=wh;){let e=r.shift();e!==void 0&&this.drop(e)&&(this.stats.hintDropped+=1)}r.push(n),this.hints.set(t,r),this.start(n,this.withCmcd(e,t,`media`),!0,Ch),this.stats.hintStarted+=1}dropHints(e){for(let t of this.hints.get(e)??[])this.drop(t)&&(this.stats.hintDropped+=1);this.hints.delete(e)}drop(e){let t=this.entries.get(e);return t?(this.entries.delete(e),t.abort.abort(),!0):!1}start(e,t,n,r){let i=new AbortController,a={started:performance.now(),first:0,end:0,hint:n,headers:Promise.resolve(),bytes:Promise.resolve(null),abort:i},o=()=>{};a.headers=new Promise(e=>o=e),a.bytes=fetch(t,{credentials:`omit`,mode:`cors`,signal:i.signal}).then(async e=>{if(a.first=performance.now(),o(),!e.ok)return null;let t=await e.arrayBuffer();return a.end=performance.now(),t}).catch(()=>null).finally(o),this.entries.set(e,a),setTimeout(()=>{this.entries.get(e)===a&&(this.entries.delete(e),i.abort(),n?this.stats.hintExpired+=1:this.stats.expired+=1)},r)}take(e){let t=Th(e),n=this.entries.get(t);return n&&this.entries.delete(t),n}destroy(){for(let e of this.entries.values())e.abort.abort();this.entries.clear(),this.hints.clear()}withCmcd(e,t,n){let{sessionId:r,contentId:i}=this.cmcd;if(!r&&!i)return e;let a=[];i&&a.push(`cid="${i}"`),a.push(`ot=${n===`init`?`i`:t===`audio`?`a`:`v`}`),a.push(`sf=h`),r&&a.push(`sid="${r}"`),a.push(`st=ll`);try{let t=new URL(e);return t.searchParams.set(`CMCD`,a.join(`,`)),t.toString()}catch{return e}}};function Dh(e,t){let n=typeof t==`function`?t:$.DefaultConfig?.loader;if(typeof n!=`function`)return;class r extends n{constructor(...e){super(...e),i(this,`served`,!1),i(this,`cancelled`,!1),i(this,`entry`,void 0),i(this,`stats`,Oh())}load(t,n,r){let i=t.rangeEnd?void 0:e.take(t.url);if(!i){super.load(t,n,r);return}this.served=!0,this.entry=i;let a=performance.now(),o=()=>{i.hint?e.stats.hintFailed+=1:e.stats.failed+=1},s=()=>{!this.cancelled&&this.served&&(i.abort.abort(),o(),this.served=!1,this.entry=void 0,super.load(t,n,r))},c=n?.loadPolicy,l=c?.maxTimeToFirstByteMs||xh,u=setTimeout(s,l);i.headers.then(()=>{clearTimeout(u);let e=c?.maxLoadTimeMs;e&&(u=setTimeout(s,Math.max(0,e-(performance.now()-a))))}),i.bytes.then(s=>{if(clearTimeout(u),this.cancelled||!this.served)return;if(!s){o(),this.served=!1,super.load(t,n,r);return}let c=this.stats;if(i.hint){e.stats.hintServed+=1;let t=performance.now(),n=Math.max(0,(i.end||t)-(i.first||t)),r=Math.max(0,(i.first||t)-a);c.loading.end=t,c.loading.first=t-n,c.loading.start=c.loading.first-r}else e.stats.served+=1,c.loading.start=a,c.loading.first=Math.max(a,i.first||a),c.loading.end=performance.now();c.loaded=c.total=s.byteLength,this.entry=void 0,r.onSuccess({url:t.url,data:s},c,t,null)})}abort(){if(this.served){this.cancelled=!0,this.stats.aborted=!0,this.entry?.abort.abort(),this.entry=void 0;return}super.abort()}}return r}function Oh(){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 kh(e){return e===`audio`?`audio`:`main`}function Ah(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 jh(e){let t=e,n=t?.preloadHint;if(!n||!t?.url||n.TYPE!==`PART`||n[`BYTERANGE-START`]!==void 0||n[`BYTERANGE-LENGTH`]!==void 0)return null;let r=n.URI;if(typeof r!=`string`||!r)return null;try{return new URL(r,t.url).toString()}catch{return null}}function 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 Nh(){return $.isSupported()}var Ph=3,Fh=1e6,Ih=20,Lh=1e4,Rh=3,zh=5,Bh=3,Vh=1e4,Hh=3e4,Uh=12e3,Wh=3e3,Gh=.02,Kh=6e3,qh=.5,Jh=3,Yh=.5,Xh=1.1,Zh=.25,Qh=5e3,$h=4e3,eg=2,tg=5,ng=2,rg=2,ig=4,ag=4,og=2e3,sg=3e4,cg=1,lg=2,ug=.5,dg=.6,fg=2,pg=1.5,mg=1e4,hg=18e4,gg=.5,_g=2;function vg(e){let t=e.config??{};return t.capLevelToPlayerSize===!0||t.capLevelOnFPSDrop===!0}var yg=8,bg=12e4,xg=6e4;function Sg(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}function Cg(){return typeof self<`u`&&self.devicePixelRatio>0?self.devicePixelRatio:1}var wg=.2,Tg=30,Eg=2,Dg=2,Og=2,kg=9,Ag=.5,jg=64,Mg=1e4,Ng=8,Pg=.6,Fg=.4,Ig=.4,Lg=2,Rg=6e4,zg=.5,Bg=3.5,Vg=300;function Hg(e){return(e?.part??e?.frag)?.stats}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 Wg(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Og;let t=Math.max(12,e.liveSyncDuration+kg);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),Gg(e,e.liveSyncDuration)}function Gg(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 Kg=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,`offlineHold`,!1),i(this,`onOffline`,null),i(this,`onOnline`,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,`headroomSamples`,[]),i(this,`headroomGranted`,!1),i(this,`lastStallAt`,0),i(this,`headroomRegrantAt`,0),i(this,`headroomUngated`,!1),i(this,`playingSince`,0),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,`stallCapBitrate`,null),i(this,`stallCapSince`,0),i(this,`stallCapTickAt`,0),i(this,`stallDownCaps`,0),i(this,`stallCapEnabled`,void 0),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.stallCapEnabled=e.stallCap!==!1,this.frameCounter=new Wm(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=uh(n)&&dh(),o=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!o){r({type:`error`,error:new a(`DRM_CLIENT`,0,e.drm?.fairplay?.licenseUrl&&i?`FairPlay cannot be played on the hls.js engine (WebKit binds keys via the media sinf box); use engine "auto" or "native"`:`DRM is required but none of the stream’s key systems is usable on this platform (WebKit takes FairPlay only; other browsers take Widevine only)`),fatal:!0});return}e.drmEnabled&&o&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&(Xe(n),rt()),this.startHls(),t!==!1&&typeof document<`u`&&(this.onVisibility=()=>{let e=this.hls;if(document.visibilityState!==`visible`||!e)return;let t=e.liveSyncPosition;if(typeof t!=`number`)return;let r=typeof e.targetLatency==`number`&&e.targetLatency>0?e.targetLatency:3;t-n.currentTime>Math.max(r*3,8)&&(n.currentTime=t)},document.addEventListener(`visibilitychange`,this.onVisibility)),typeof window<`u`&&(this.onOffline=()=>{this.offlineHold=!0,this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),this.lastAdvanceMs=this.lastAdvanceMs?Date.now():0,this.resetStarvationWindow(),this.clearKick()},this.onOnline=()=>{if(this.offlineHold&&(this.offlineHold=!1,this.networkRecoveries=0,this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),!this.stopped&&this.hls&&this.loadStarted&&!this.loadSuspended)){this.lastAdvanceMs=Date.now(),this.lastFragLoadingMs=0,this.resetStarvationWindow(),this.resetChaseWindow(),this.clearKick();try{this.hls.startLoad(-1)}catch{}}},window.addEventListener(`offline`,this.onOffline),window.addEventListener(`online`,this.onOnline),Lm()||this.onOffline()),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}},Qh))}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=Cg(),t=matchMedia(`(resolution: ${e}dppx)`);if(typeof t.addEventListener!=`function`)return;let n=()=>{this.onMediaResize(),this.watchDprChanges()};t.addEventListener(`change`,n),this.dprMedia=t,this.onDprChange=n}unwatchDprChanges(){this.dprMedia&&this.onDprChange&&this.dprMedia.removeEventListener(`change`,this.onDprChange),this.dprMedia=null,this.onDprChange=null}clampOverSeek(){let e=this.hls;if(!e||this.chaseSuspended||(e.levels[e.currentLevel]??e.levels[e.loadLevel])?.details?.live!==!0)return;let t=e.liveSyncPosition;if(typeof t!=`number`||!Number.isFinite(t))return;let{video:n}=this.deps;n.currentTime<=t+Ag||(n.currentTime=t)}reanchorPartTimeline(e,t){let{frag:n,part:r}=t;if(!r||r.index!==0||n.type!==`main`||typeof n.sn!=`number`)return;let i=e.levels[n.level]?.details;if(!i?.live)return;let a=r.elementaryStreams.video??r.elementaryStreams.audiovideo??r.elementaryStreams.audio;if(!a)return;let o=n.sn,s=i.fragments.find(e=>e&&e.sn===o)??(i.fragmentHint?.sn===o?i.fragmentHint:void 0);if(!s)return;let c=a.startPTS-s.start;if(!(!Number.isFinite(c)||Math.abs(c)<Gh)){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=uh(this.deps.video)&&dh(),d={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,liveDurationInfinity:!0,maxBufferHole:.5,maxLiveSyncPlaybackRate:u?1:1.1,abrEwmaDefaultEstimate:this.startEstimate(),capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...l?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:Ye.video,audioRobustness:Ye.audio,videoEncryptionScheme:Ye.scheme,audioEncryptionScheme:Ye.scheme},...We()?{requestMediaKeySystemAccessFunc:Je(e)}:{},licenseXhrSetup:(e,a)=>{let o=performance.now(),s=()=>{e.open(`POST`,this.licenseUrl??a,!0),e.setRequestHeader(`x-api-key`,n.apiKey),e.setRequestHeader(`X-Match-Urn`,t.matchUrn),e.setRequestHeader(`X-Device-Id`,r),i&&e.setRequestHeader(`X-User-Id`,i),this.licenseRequested=!0,e.addEventListener(`loadend`,()=>{this.licenseTimeMs===0&&(this.licenseTimeMs=Math.max(1,Math.round(performance.now()-o)))})},{freshLicenseUrl:c}=this.deps;if(!c||!_h(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),Vh)});return Promise.race([c().catch(()=>void 0),d]).finally(()=>clearTimeout(u)).then(e=>{if(!this.hls||this.hls!==l)throw Error(`havik-player: engine torn down during refresh`);e&&(this.licenseUrl=e),s()})}}:{},...t.analytics?.sid?{cmcd:{sessionId:t.analytics.sid,contentId:t.matchUrn,useHeaders:!1}}:{},...s};this.prefetch?.destroy(),this.prefetch=null;let f=!1,p=!1,m=l&&this.deps.mediaDuringKey!==!1,h=this.deps.preloadHints!==!1;if((m||h)&&!d.fLoader){let e=new Eh({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=Dh(e,d.loader);n&&(this.prefetch=e,f=m,p=h,d.fLoader=n)}Wg(d),this.catchUpRate=typeof d.maxLiveSyncPlaybackRate==`number`?d.maxLiveSyncPlaybackRate:1,this.catchUpEngaged=!1,this.catchUpRate>1&&(d.maxLiveSyncPlaybackRate=1),this.sizeCapManaged=d.capLevelToPlayerSize!==!0,this.fpsCapManaged=!(s&&`capLevelOnFPSDrop`in s),this.loadStarted=d.autoStartLoad!==!1;let g=new $(d);if(this.hls=g,this.armHoldBack(g,d),g.on($.Events.FRAG_PARSED,(e,t)=>this.reanchorPartTimeline(g,t)),g.on($.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,l&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&this.dropLevelsWidevineCannotPlay(g),this.measureLadder(g),this.applySizeCap(),this.loadSuspended=!1,e.paused&&this.schedulePauseSuspend(),c({type:`ready`})}),g.on($.Events.FRAG_BUFFERED,(e,t)=>{t?.frag?.type===`main`&&(this.kickKind!==`dead`&&this.clearKick(),(this.mediaRecoveries>0||this.networkRecoveries>0||this.licenseRecoveries>0||this.starvationKicks>0||this.starvationRebuilds>0)&&!this.recoveryResetTimer&&(this.recoveryResetTimer=setTimeout(()=>{this.mediaRecoveries=0,this.networkRecoveries=0,this.licenseRecoveries=0,this.starvationKicks=0,this.starvationRebuilds=0,this.recoveryResetTimer=null},Hh)))}),g.on($.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),g.on($.Events.FRAG_LOADED,(e,t)=>{t?.frag?.type===`main`&&(this.mainFragsSinceTick+=1,this.bwFragsLoaded+=1,this.maybeRememberBandwidth(!1));let n=t?.frag,r=Hg(t),i=r?.loaded;typeof i==`number`&&(this.bytesLoaded+=i),!this.reportedFirstBytes&&typeof i==`number`&&i>0&&(this.reportedFirstBytes=!0,c({type:`firstBytes`}));let a=r?.loading;a&&a.end>0&&a.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(a.end-a.start))),this.requestTimesMs.length>jg&&this.requestTimesMs.shift()),this.sampleHoldBack(t),this.sampleHeadroom(t);let o=n?.url;if(o){let e=Bm(o);e&&(this.cdnHost=e)}}),g.on($.Events.LEVEL_LOADED,(e,t)=>{let n=t?.stats?.loaded;if(typeof n==`number`&&(this.playlistBytesLoaded+=n),this.reportedFirstPlaylist||(this.reportedFirstPlaylist=!0,c({type:`firstPlaylist`})),this.detectedLowLatency)return;let r=t.details;r?.partList?.length||(r?.partTarget??0)>0?(this.detectedLowLatency=!0,c({type:`lowLatencyDetected`,value:!0}),this.headroomUngated&&(this.headroomUngated=!1,this.applySizeCapUnlessPending())):r&&!this.headroomUngated&&(this.headroomUngated=!0,this.applySizeCapUnlessPending())}),g.on($.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.prefetch&&p){let e=this.prefetch,t=this.deps.video,n=(n,r)=>{if(t.paused)return;let i=n;if(!i?.live||!i.partList?.length||typeof i.edge!=`number`)return;let a=t.buffered,o=a.length?a.end(a.length-1):0;if(i.edge-o>Ph*(i.partTarget||.5))return;let s=jh(n);s&&e.prefetchHint(s,r)};g.on($.Events.LEVEL_LOADED,(e,t)=>{t.level===g.loadLevel&&n(t.details,`main`)}),g.on($.Events.AUDIO_TRACK_LOADED,(e,t)=>{t?.id===g.audioTrack&&n(t?.details,`audio`)}),g.on($.Events.LEVEL_SWITCHING,()=>e.dropHints(`main`)),g.on($.Events.AUDIO_TRACK_SWITCHING,()=>e.dropHints(`audio`))}if(this.prefetch&&f){let e=this.prefetch;g.on($.Events.KEY_LOADING,(t,n)=>{let r=n?.frag,i=kh(r?.type);if(r&&e.isActive(i))for(let t of Ah(g,r))e.prefetch(t.url,i,t.kind)}),g.on($.Events.KEY_LOADED,(t,n)=>e.keyUsable(kh(n?.frag?.type)))}g.on($.Events.KEY_LOADED,()=>{l&&!this.reportedDrmReady&&(this.reportedDrmReady=!0,c({type:`drmReady`}))}),this.endWatchdog&&clearInterval(this.endWatchdog),this.endWatchdog=setInterval(()=>{this.checkEndStale(),this.checkStarvation(),this.updateCatchUpBand(),this.checkFutileChase(),this.adaptHoldBack(),this.reviewSizeCapHeadroom(),this.releaseStallCap(),this.checkFrameDrops()},Wh),g.on($.Events.LEVEL_SWITCHED,(e,t)=>{this.renditionSwitches+=1;let n=this.lastLevelIndex>=0?g.levels[this.lastLevelIndex]:void 0,r=g.levels[t.level];n&&r&&r.bitrate!==n.bitrate&&(r.bitrate>n.bitrate?this.upshifts+=1:this.downshifts+=1),this.lastLevelIndex=t.level,this.armFrameDropGrace(),c({type:`qualitychange`,index:t.level})}),g.on($.Events.AUDIO_TRACK_SWITCHED,(e,t)=>c({type:`audiotrackchange`,id:t.id})),g.on($.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>c({type:`texttrackchange`,id:t.id})),g.on($.Events.ERROR,(e,t)=>this.onError(t)),g.loadSource(t.manifestUrl),g.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(t){if(e==null)this.bitrateCapLevel=-1;else{let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),this.bitrateCapLevel=n}this.pushCap()}}sizeCapCover(){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=Cg(),s=a.ignoreDevicePixelRatio?1:o;return s=Math.min(s,a.maxDevicePixelRatio??1/0),{cover:Ll.getMaxLevelByMediaSize(e.levels,r*s,i*s),deviceRatio:o}}sizeCapCoverLevel(){return this.sizeCapCover()?.cover??null}computeSizeCapTarget(){let e=this.hls,t=this.sizeCapCover();if(!e||!t)return null;let{cover:n,deviceRatio:r}=t,i=this.deps.sizeCapHeadroom,a=i==null||Number.isNaN(i);if(a&&r>=lg)return n;if(a)return this.headroomUngated||this.headroomGranted?Sg(e.levels,n,cg):n;let o=i===1/0?e.levels.length:Math.max(0,Math.floor(i));return Sg(e.levels,n,o)}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?og:sg;this.capTimer=setTimeout(()=>{this.capTimer=null;let n=this.computeSizeCapTarget();n===e||t===sg&&n!=null&&n<e?this.applySizeCap():this.onMediaResize()},t)}measureLadder(e){let t=e.levels.map(e=>e.height).filter(e=>!!e);this.ladderHeights=t.length?[...new Set(t)].sort((e,t)=>e-t):void 0,this.ladderTopBitrateKbps=e.levels.length?Math.round(Math.max(...e.levels.map(e=>e.bitrate))/1e3):0}dropLevelsWidevineCannotPlay(e){this.removeLevelsWhere(e,e=>it(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&Ze(e)!==`avc`&&!!Ze(e)));for(let n of t)nt(n).then(t=>{t||this.hls!==e||this.removeLevelsWhere(e,e=>e===n)&&(this.measureLadder(e),this.applySizeCap())})}removeLevelsWhere(e,t){let n=e.levels??[],r=[],i=new Set;if(n.forEach((e,n)=>{let a=e.videoCodec;a&&Ze(a)&&t(a)&&(r.push(n),i.add(a))}),!r.length)return!1;let a=[...i].join(`, `);if(!n.some((e,t)=>r.includes(t)?!1:!Ze(e.videoCodec)||it(e.videoCodec)===!0))return console.warn(`havik-player: every rendition is ${a}, which Widevine may not play on this browser; keeping them`),!1;for(let t=r.length-1;t>=0;--t)e.removeLevel(r[t]);return console.info(`havik-player: skipped ${r.length} rendition(s) Widevine cannot play on this browser (${a})`),!0}defaultHeadroomApplies(){let e=this.deps.sizeCapHeadroom;return e!=null&&!Number.isNaN(e)||this.headroomUngated?!1:Cg()<lg}applySizeCapUnlessPending(){this.capTimer||this.applySizeCap()}sampleHeadroom(e){if(!this.sizeCapManaged||!this.defaultHeadroomApplies()||e.frag?.type!==`main`||typeof e.frag.level!=`number`||typeof document<`u`&&document.hidden)return;let t=e.part?e.part.duration:this.detectedLowLatency?0:e.frag.duration;if(typeof t!=`number`||!(t>0))return;let n=Hg(e)?.loading;if(!n||!(n.start>0)||!(n.end>=n.start))return;let r=this.hls?.levels?.[e.frag.level]?.bitrate;if(!(typeof r==`number`&&r>0))return;let i=(n.end-n.start)/(t*1e3);this.headroomSamples.push({t:Date.now(),ratio:i,bitrate:r}),this.headroomSamples.length>256&&this.headroomSamples.shift()}onPlaybackStall(e){let t=Date.now();this.deps.video.seeking||!this.playingSince||t-this.playingSince<mg||(this.lastStallAt=t,this.stepStallCapDown(t,e),this.headroomGranted&&(this.headroomGranted=!1,this.applySizeCapUnlessPending()))}stallCapLevel(e){if(this.stallCapBitrate==null)return-1;let t=-1;return e.levels.forEach((e,n)=>{e.bitrate<=this.stallCapBitrate&&(t=n)}),t<0?0:t}stepStallCapDown(e,t){let n=this.hls;if(!n||!this.stallCapEnabled||vg(n)||!n.autoLevelEnabled||typeof t==`number`&&t>=gg||this.isLiveEdgeWait(n,t??0))return;this.stallCapBitrate!=null&&(this.stallCapSince=e);let r=Math.max(n.levels[n.currentLevel]?.bitrate??0,n.levels[n.loadLevel]?.bitrate??0);if(!(r>0))return;let i=n.levels.map(e=>e.bitrate).filter(e=>e>0&&e<r).sort((e,t)=>t-e)[0];i!=null&&(this.stallCapBitrate!=null&&i>=this.stallCapBitrate||(this.stallCapBitrate=i,this.stallCapSince=e,this.stallDownCaps+=1,this.pushCap()))}isLiveEdgeWait(e,t){let n=e.latestLevelDetails;if(!n?.live)return!1;let r=n.partTarget||n.targetduration;return!(r>0)||!(n.edge>0)?!1:n.edge-(this.deps.video.currentTime+t)<_g*r}releaseStallCap(){let e=this.hls,t=Date.now(),n=this.stallCapTickAt;if(this.stallCapTickAt=t,!e||this.stallCapBitrate==null)return;if(this.deps.video.paused||this.loadSuspended||this.offlineHold){n&&(this.stallCapSince+=t-Math.max(n,this.stallCapSince));return}if(t-this.stallCapSince<hg)return;let r=this.stallCapBitrate,i=e.levels.map(e=>e.bitrate).filter(e=>e>r).sort((e,t)=>e-t)[0];this.stallCapBitrate=i??null,this.stallCapSince=t,this.pushCap()}reviewSizeCapHeadroom(){let e=Date.now(),{video:t}=this.deps;!t.paused&&!t.seeking&&t.readyState>=3?this.playingSince||=e:this.playingSince=0;let n=this.hls;if(!n||!this.sizeCapManaged)return;if(!this.defaultHeadroomApplies()){this.headroomGranted=!1,this.headroomSamples=[];return}this.headroomSamples=this.headroomSamples.filter(t=>t.t>=e-Mg);let r=this.headroomEarned(n,e);r!==this.headroomGranted&&(r||(this.headroomRegrantAt=e+xg),this.headroomGranted=r,this.applySizeCapUnlessPending())}headroomEarned(e,t){if(t-this.lastStallAt<bg||!this.headroomGranted&&t<this.headroomRegrantAt||!this.headroomGranted&&this.headroomSamples.length<yg)return!1;let n=e.levels,r=this.sizeCapCoverLevel();if(r==null)return this.headroomGranted;let i=Sg(n,r,cg);if(i===r)return this.headroomGranted;let a=n[i]?.bitrate,o=e.bandwidthEstimate,s=this.headroomGranted?pg:fg;if(!(a>0)||!(o>=s*a))return!1;let c=e=>Mh([...e].sort((e,t)=>e-t),90);if(this.headroomGranted){let e=this.headroomSamples.filter(e=>e.bitrate>=a).map(e=>e.ratio);return e.length<yg||c(e)<=dg}let l=[];for(let e of this.headroomSamples)e.bitrate<a&&l.push(e.ratio*(a/e.bitrate));return l.length>=yg&&c(l)<=ug}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)],[`stall`,this.stallCapLevel(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,stallDownCaps:this.stallDownCaps,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;i&&i.height>0&&(n.maxLevelHeight=i.height,!vg(e)&&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.offlineHold||!Lm()){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>Kh&&this.suspendChasing(),e>Uh&&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.offlineHold||!Lm()){this.resetStarvationWindow();return}let n=Date.now(),r=this.lastAdvanceMs!==0&&n-this.lastAdvanceMs<Kh,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>$h,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=Um(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>ig&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=ng&&(this.clearKick(),this.starvationRebuilds<rg)){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>=eg,d=!i&&this.deadTicks>=ig&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=ag;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=tg))){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||this.offlineHold)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>qh?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=qh&&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=Dg,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||this.offlineHold||t.paused||!e.autoLevelEnabled||typeof document<`u`&&document.hidden){this.resetFrameDropWindow();return}let{totalFrames:n,dropped:r}=Um(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<Tg||o<0){this.fpsBadTicks=0;return}if(this.fpsGraceTicks>0){--this.fpsGraceTicks,this.fpsBadTicks=0;return}if(o<=wg*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<Eg)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||this.offlineHold||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(Xh,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=Yh){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<Jh)return;this.resetChaseWindow();let a=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;if(!(a>1))return;let o=e.targetLatency;if(typeof o!=`number`||!(o>0))return;let s=Math.min(n,a-1);s<o+Zh||(console.warn(`havik-player: catch-up at ${r}x not gaining on the live edge (latency ${n.toFixed(1)}s); holding at ${s.toFixed(1)}s`),this.liveRetargets+=1,e.targetLatency=s,this.deps.emit({type:`livetargetchange`,change:{targetSeconds:s,previousSeconds:o,reason:`futile-chase`}}))}armHoldBack(e,t){this.headroomSamples=[],this.headroomGranted=!1,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>=Vg))return;let r=typeof t==`number`&&t>0?t:this.holdBackBase,i=Math.min(this.holdBackCeiling(e),this.holdBackBase+zg);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:Bg,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=Hg(e)?.loading;if(!r||!(r.start>0)||!(r.end>0))return;let i=r.first>r.start?r.first:r.end,a=Math.max(0,i-r.start)/(n*1e3);this.holdBackSamples.push({t:Date.now(),ratio:a}),this.holdBackSamples.length>256&&this.holdBackSamples.shift()}adaptHoldBack(){if(!this.holdBackEnabled)return;let e=this.hls;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||this.offlineHold||typeof document<`u`&&document.hidden){this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[];return}let t=Date.now(),n=t-Mg,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<Ng){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>=Pg&&u>=Fg){if(this.holdBackFastSince=0,this.holdBackSlowTicks+=1,this.holdBackSlowTicks<Lg)return;this.holdBackSlowTicks=0;let t=Math.ceil((s-o)/zg),n=Math.ceil((a-o)/zg-1e-9);if(n>this.holdBackStepCount&&(this.holdBackStepCount=n),this.holdBackStepCount>=t)return;this.holdBackStepCount+=1;let r=Math.min(s,o+this.holdBackStepCount*zg);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<Rg||(this.holdBackFastSince=t,this.holdBackStepCount===0||a!==this.holdBackApplied))return;--this.holdBackStepCount;let f=Math.max(o,o+this.holdBackStepCount*zg);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?Fh:ze()??Fh}maybeRememberBandwidth(e){if(this.deps.rememberBandwidth===!1||this.bwFragsLoaded<Ih)return;let t=Date.now();if(!e&&t-this.bwSavedAt<Lh)return;let n=this.hls?.bandwidthEstimate;typeof n!=`number`||!Number.isFinite(n)||n<=0||(this.bwSavedAt=t,Be(n))}destroy(){if(this.maybeRememberBandwidth(!0),this.detachFrames?.(),this.detachFrames=null,this.prefetch?.destroy(),this.prefetch=null,this.clearRecoveryReset(),this.capTimer&&=(clearTimeout(this.capTimer),null),this.capObserver&&=(this.capObserver.disconnect(),null),this.unwatchDprChanges(),this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onOffline&&typeof window<`u`&&(window.removeEventListener(`offline`,this.onOffline),this.onOffline=null),this.onOnline&&typeof window<`u`&&(window.removeEventListener(`online`,this.onOnline),this.onOnline=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(),this.armFrameDropGrace()}}onError(e){if(e.details===$.ErrorDetails.BUFFER_STALLED_ERROR&&this.onPlaybackStall(e.buffer),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(!Lm()&&(e.response?.code??0)===0){this.offlineHold=!0,this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null);return}if(this.networkRecoveries<zh){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<Rh){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(yh(e.networkDetails)):void 0;return new a(t===`DRM`?c(n,o):t===`NETWORK`&&n===0?`NETWORK`:n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`,{detail:r,...o?{serverCode:o}:{}})}},qg=15e3,Jg=6e5,Yg=3e5,Xg=100,Zg=1,Qg=1e3,$g=3e4,e_=1e3,t_={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},n_={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`},r_=new Set([`INVALID_URN`,`NOT_FOUND`,`GEO_DENIED`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),i_={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 a_(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 o_=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),s_=new Set,c_=new Set,l_=new Set,u_=e=>`this page's Content-Security-Policy blocks QoE beacons. Add ${e} to connect-src; until then none are sent.`;function d_(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(s_.has(t)&&!c_.has(t)){c_.add(t),b(u_(new URL(t).origin));for(let e of l_)e.noteCspBlocked()}}function f_(e,t){return b(t,e),{disabledReason:t}}function p_(e,t,n){if(n)return t&&!o_(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return f_(`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=a_(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return f_(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 m_=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??qg,idleMs:e.idleMs??Jg},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(),Qg),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&&s_.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,d_),l_.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,Yg);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(Zg,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(Zg,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(Zg,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:i_[e]??`PLAYER_STATE_UNSPECIFIED`,toState:i_[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:t_[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<e_}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(Zg,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=Zg),this.firstPlaylistMs>0&&(this.firstPlaylistMs=Zg),this.firstFragLoadMs>0&&(this.firstFragLoadMs=Zg),this.drmSetupMs>0&&(this.drmSetupMs=Zg))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(Zg,this.now()-this.startupAnchorMs))}noteFirstPlaylist(){this.firstPlaylistMs===0&&(this.firstPlaylistMs=Math.max(Zg,this.now()-this.startupAnchorMs))}noteDrmReady(){this.drmSetupMs===0&&(this.drmSetupMs=Math.max(Zg,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(Zg,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(r_.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=i_[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=n_[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,l_.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<=$g&&(i.abandonAfterStallMs=Math.max(Zg,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=$g&&(i.abandonAfterErrorMs=Math.max(Zg,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?.(u_(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&c_.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>Xg;){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 h_(){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 g_(){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 __(){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 v_(e){let t=h_(),n={deviceClass:g_(),integration:t.integration,...__()};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 y_(){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 b_=`2.28.0`,x_={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`},S_={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 C_(e,t){let n={...x_,...t};for(let t of Object.keys(S_))e.style.setProperty(S_[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var w_=`havik-player-styles`,T_=`
|
|
47
47
|
.havik-player{position:relative;display:block;width:100%;background:var(--havik-bg,#0e0f13);
|
|
48
48
|
color:var(--havik-text,#fff);font-family:var(--havik-font,system-ui,sans-serif);
|
|
49
49
|
overflow:hidden;line-height:1.4;-webkit-tap-highlight-color:transparent}
|
|
@@ -171,5 +171,5 @@ Schedule: ${a.map(e=>Dp(e))} pos: ${this.timelinePos}`),s.length&&this.log(`Remo
|
|
|
171
171
|
.havik-menu__item:hover{background:var(--havik-surface-muted,#2a2c36)}
|
|
172
172
|
.havik-menu__item[aria-checked="true"]{color:var(--havik-accent,#E1B600);font-weight:600}
|
|
173
173
|
.havik-menu__item[aria-checked="true"]::after{content:'✓'}
|
|
174
|
-
`,x_=new WeakMap;function S_(e=document,t){let n=e.querySelector(`style#${y_}`);if(n&&(!t||x_.get(n)===t))return;let r=e.createElement(`style`);r.id=y_,t&&(r.nonce=t,r.setAttribute(`nonce`,t)),r.textContent=b_,x_.set(r,t),n?n.replaceWith(r):e.head.appendChild(r)}var C_={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 w_(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${C_[e]}</svg>`}var T_=3e3,E_=250,D_=new Set([`GONE`,`NOT_FOUND`,`GEO_DENIED`,`INVALID_URN`,`UNAUTHORIZED`,`DRM_DEVICE_REVOKED`]);function O_(e){let t=`This match isn't available in your country`;return e?`${t} (${e})`:t}var k_=`This device can't play protected video`;function A_(e){return new j_(e)}var j_=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,`offlineMessage`,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??T_,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,this.offlineMessage=e.offlineMessage??`No internet connection — waiting to reconnect`,S_(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=w_(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=w_(`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=w_(`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(`offline`,()=>this.syncState())),this.offFns.push(this.player.on(`online`,()=>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)},E_)}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()}isGone(){return this.player.state===`error`&&this.lastError?.code===`GONE`}syncStatus(e){let t=null;if(this.statusOverlays){let n=e===`ended`||this.isGone(),r=this.player.offline&&!n&&e!==`idle`,i=!this.hasPlayed&&(e===`paused`||e===`waiting`);n?t=`ended`:r&&!i?t=`offline`: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.isGone()?this.endedMessage:this.player.endedReason===`interrupted`?this.interruptedMessage:this.endedMessage:e===`offline`?this.offlineMessage:e===`waiting`?this.hasPlayed?`Reconnecting — please stand by`:`Starting soon…`:e===`error`?this.errorMessage===void 0?this.lastError?.code===`GEO_DENIED`?O_(this.lastError.country):this.lastError?.code===`DRM_DEVICE_REVOKED`?k_: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=w_(`play`),e.addEventListener(`click`,()=>void this.player.play()),n.append(e)}else{let r=this.doc.createElement(`div`);if(r.className=`havik-status__msg`,r.textContent=t??``,n.append(r),e===`error`&&this.lastError&&!D_.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${w_(`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=`${M_(this.video.currentTime)} / ${M_(this.video.duration)}`)}syncLive(){let e=this.player.getStats(),t=e.isLive!==!1,n=this.isGone(),r=this.player.state===`ended`||n,i=!t&&!this.streamEnded()&&!n;this.live.style.display=t&&!r?``:`none`,this.time.style.display=i?``:`none`,this.seek.style.display=i?``:`none`,this.live.classList.toggle(`is-live`,e.atLiveEdge!==!1&&t)}onSeekDown(e){let t=this.seekableRange();if(!t)return;e.preventDefault(),this.scrubbing=!0;let n=e=>this.seekToPointer(e,t),r=()=>{this.scrubbing=!1,this.doc.removeEventListener(`pointermove`,n),this.doc.removeEventListener(`pointerup`,r)};this.doc.addEventListener(`pointermove`,n),this.doc.addEventListener(`pointerup`,r),this.seekToPointer(e,t)}seekToPointer(e,t){let n=this.seek.getBoundingClientRect(),r=n.width>0?Math.min(1,Math.max(0,(e.clientX-n.left)/n.width)):0;this.seekPlayed.style.width=`${(r*100).toFixed(2)}%`,this.seekThumb.style.left=`${(r*100).toFixed(2)}%`,this.video.currentTime=t.start+r*(t.end-t.start)}onSeekKey(e){e.key===`ArrowLeft`?(this.nudge(-5),e.preventDefault()):e.key===`ArrowRight`&&(this.nudge(5),e.preventDefault())}nudge(e){let t=this.seekableRange();t&&(this.video.currentTime=Math.min(t.end,Math.max(t.start,this.video.currentTime+e)))}toggleMenu(e){if(this.openMenu===e){this.closeMenu();return}this.openMenu=e,this.renderMenu(e),this.menu.hidden=!1,this.show()}closeMenu(){this.openMenu=null,this.menu.hidden=!0,this.menu.replaceChildren()}renderMenu(e){e===`quality`?this.renderQualityMenu():e===`audio`?this.renderAudioMenu():this.renderCcMenu()}menuItem(e,t,n){let r=this.doc.createElement(`button`);r.type=`button`,r.className=`havik-menu__item`,r.setAttribute(`role`,`menuitemradio`),r.setAttribute(`aria-checked`,t?`true`:`false`);let i=this.doc.createElement(`span`);return i.textContent=e,r.append(i),r.addEventListener(`click`,()=>{n(),this.closeMenu()}),r}renderQualityMenu(){let e=this.player.getQualityLevels(),t=this.player.getCurrentQuality(),n=this.doc.createElement(`div`);n.className=`havik-menu__title`,n.textContent=`Quality`,this.menu.replaceChildren(n,this.menuItem(`Auto`,t===-1,()=>this.player.setQuality(`auto`)));for(let n of e)this.menu.append(this.menuItem(N_(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(P_(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(F_(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=w_(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 M_(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 N_(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function P_(e){return e.name||e.lang||`Track ${e.id}`}function F_(e){return e.name||e.lang||`Track ${e.id}`}var I_=6e3,L_=45e3,R_=2e3,z_=3,B_=5e3,V_=2e3,H_=48e4,U_=`keySystemLicenseRequestFailed`,W_=new Set([`GONE`,`NOT_FOUND`,`INVALID_URN`,`UNAUTHORIZED`,`GEO_DENIED`,`DRM_DEVICE_REVOKED`]);function G_(e){return!W_.has(e)}function K_(e){if(e.env!==void 0&&e.baseUrl!==void 0)throw new a(`INTERNAL`,0,`createPlayer: pass env OR baseUrl, not both (got env=${JSON.stringify(e.env)} and baseUrl=${JSON.stringify(e.baseUrl)})`);if(e.env!==void 0)return ht(e.env);if(!e.baseUrl)throw new a(`INTERNAL`,0,`createPlayer: env or baseUrl is required (env: 'integration' | 'production')`);return e.baseUrl}async function q_(e){if(!e.video||typeof e.video.play!=`function`)throw new a(`INTERNAL`,0,`createPlayer: opts.video must be an HTMLVideoElement`);let t=K_(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 J_({...e,baseUrl:t});return await n.start(),n}var J_=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),i(this,`connectivity`,null),i(this,`failedWhileOffline`,!1),this.opts=e}get state(){return this._state}get offline(){return!Lm()}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.watchConnectivity(),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 this.destroy(),t}}resolveOptions(){return{baseUrl:this.opts.baseUrl,matchUrn:this.opts.matchUrn,credential:this.opts.credential,signal:this.abort.signal,apiHeaders:this.opts.apiHeaders}}beginArming(e,t,n=!1){let r=this.opts.liveStateEvents===!1?void 0:this.opts.eventsBaseUrl??we(this.opts.baseUrl);r?this.armWithSse(e,r,t,n):this.beginArmingByPolling(e)}beginArmingByPolling(e){te({...this.resolveOptions(),signal:this.abort.signal,waitForLive:this.buildWaitConfig(e)}).then(t=>{if(!(this.destroyed||this.abort.signal.aborted||e!==this.loadGen))return this.onResolved(t,e)}).catch(t=>{this.destroyed||this.abort.signal.aborted||e!==this.loadGen||this.fail(t instanceof a?t:new a(`INTERNAL`,0,String(t)))})}armWithSse(e,t,n,r=!1){let i=!1,o=!1,s=new AbortController;this.armFallbackCtrl=s,this.setState(`waiting`);let c=this.opts.waitForLive,l=c&&c!==!0?c.kickoffAt:void 0,d=typeof l==`number`?l:typeof l==`string`?Date.parse(l):NaN,f=n??(Number.isFinite(d)?d:void 0);setTimeout(()=>{i||this.destroyed||e!==this.loadGen||this.emit(`waiting`,{phase:r?`unavailable`:`tooEarly`,retryInMs: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)};_(I_),this.armingSub=Ce({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()*R_)},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=Km(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}=c_(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 l_({endpoint:o,sid:r,player:t.name===`native`?`PLAYER_SAFARI_NATIVE`:`PLAYER_HLSJS`,sdkVersion:h_,environment:p_(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()??zm,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()),m_().then(e=>l.noteEnvironment(e)),this.opts.autoplay===!1&&l.noteAutoplay(`AUTOPLAY_RESULT_NOT_ATTEMPTED`)}currentPresentation(){let e=this.opts.video;if(typeof document<`u`&&document.pictureInPictureElement===e)return`pip`;let t=typeof document<`u`?document.fullscreenElement:null;return e.webkitDisplayingFullscreen===!0||t&&(t===e||t.contains(e))?`fullscreen`:`inline`}createEngine(e,t,n=!1){let r={...this.opts.hlsConfig};this.opts.startLevel!=null&&(r.startLevel=this.opts.startLevel),this.opts.liveLatencyTarget!=null&&(r.liveSyncDuration=this.opts.liveLatencyTarget);let i={video:this.opts.video,descriptor:e,credential:t,deviceId:De(),userId:this.opts.userId,lowLatency:this.opts.lowLatency===void 0||this.opts.lowLatency===`auto`||this.opts.lowLatency,snapToLiveOnRefocus:this.opts.snapToLiveOnRefocus,rememberBandwidth:this.opts.rememberBandwidth,sizeCapHeadroom:this.opts.sizeCapHeadroom,adaptiveHoldBack:this.opts.adaptiveHoldBack,adaptiveHoldBackCeiling:this.opts.adaptiveHoldBackCeiling,stallCap:this.opts.stallCap,mediaDuringKey:this.opts.mediaDuringKey,preloadHints:this.opts.preloadHints,debug:this.opts.debug,deferLoad:n,hlsConfig:r,emit:e=>this.onEngineEvent(e),freshLicenseUrl:()=>this.refreshLicense()},o=this.opts.engine??`auto`;if(o===`native`)return new ch(i);if(o===`hls`)return new Vg(i);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&ah(this.opts.video)&&oh()||!e.drmEnabled&&sh()&&ah(this.opts.video))return new ch(i);if(Oh())return new Vg(i);if(ah(this.opts.video))return new ch(i);throw new a(`INTERNAL`,0,`no supported HLS playback engine in this browser`)}onEngineEvent(e){if(!this.destroyed)switch(e.type){case`firstPlaylist`:this.analyticsSession?.noteFirstPlaylist();break;case`firstBytes`:this.analyticsSession?.noteFirstBytes();break;case`drmReady`:this.analyticsSession?.noteDrmReady(),this.staleLicenseReloaded=!1;break;case`ready`:this.analyticsSession?.noteReady(),this.emit(`ready`),(this.opts.autoplay!==!1||this.playRequested)&&this.play();break;case`lowLatencyDetected`:this._descriptor&&(this._descriptor.isLowLatency=e.value);break;case`livetargetchange`:this.emit(`latencytargetchange`,e.change);break;case`qualitychange`:this.emit(`qualitychange`,e.index);break;case`audiotrackchange`:this.emit(`audiotrackchange`,e.id);break;case`texttrackchange`:this.emit(`texttrackchange`,e.id);break;case`ended`:this.onStreamEnded();break;case`error`:{let t=e.fatal&&this.isStaleLicenseDenial(e);if(this.analyticsSession?.noteError(e.error.code,e.error.message,e.fatal&&!t,e.error.httpStatus??0,Math.round(this.opts.video.currentTime*1e3),e.detail),t){this.staleLicenseReloaded=!0;let t=this.loadGen;this.emit(`warning`,e.error),Promise.resolve().then(()=>{if(!(this.destroyed||t!==this.loadGen)&&this._state!==`error`&&this._state!==`ended`)return this.reload().catch(()=>void 0)})}else e.fatal?this.fail(e.error):this.emit(`warning`,e.error);break}}}startLiveState(e){if(this.opts.liveStateEvents===!1)return;let t=this.opts.eventsBaseUrl??we(this.opts.baseUrl);if(!t)return;this.closeLiveState();let n=0,r=!1;this.liveStateSub=Ce({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onState:t=>{this.destroyed||e!==this.loadGen||(t.state===`gone`?this.onStreamEnded(!0,t.reason??`match_ended`):t.state===`ended`?this.onStreamEnded(!1,t.reason):t.state===`live`&&this.endedHandled&&this.scheduleRejoin(e))},onAlive:()=>{n=0,r=!1},onError:i=>{if(!(this.destroyed||e!==this.loadGen||r)&&!this.endedHandled){if(i instanceof xe&&(i.terminal||i.status===404)){r=!0,this.emit(`warning`,new a(o(i.status),i.status,`live-state events answered HTTP ${i.status} for ${this.opts.matchUrn}: the match is `+(i.terminal?`gone, so the subscription stopped`:`not in the catalog (ended and dropped, or not listed yet), so it retries every 5 min`)+` — end-of-stream detection falls back to the HLS staleness watchdog.`));return}n+=1,n>=z_&&(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}watchConnectivity(){this.connectivity||(this.connectivity=Rm(),this.connectivity.onChange(e=>{if(this.destroyed)return;if(!e){this.emit(`offline`);return}if(this.emit(`online`),this._state!==`error`||!this._lastError)return;let t=this._lastError.code;G_(t)&&(t===`NETWORK`||this.failedWhileOffline)&&this.retry().catch(()=>void 0)}))}watchReturn(){this.onReturnVisible||typeof document>`u`||this.opts.liveStateEvents!==!1&&(document.visibilityState===`hidden`&&(this.hiddenAtMs=Date.now()),this.onReturnVisible=()=>{if(document.visibilityState===`hidden`){this.hiddenAtMs??=Date.now();return}let e=this.hiddenAtMs;this.hiddenAtMs=null,e!=null&&Date.now()-e>=B_&&this.resyncLiveState()},this.onReturnPageShow=e=>{e.persisted&&this.resyncLiveState()},document.addEventListener(`visibilitychange`,this.onReturnVisible),typeof window<`u`&&window.addEventListener(`pageshow`,this.onReturnPageShow))}unwatchReturn(){this.onReturnVisible&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,this.onReturnVisible),this.onReturnPageShow&&typeof window<`u`&&window.removeEventListener(`pageshow`,this.onReturnPageShow),this.onReturnVisible=null,this.onReturnPageShow=null,this.hiddenAtMs=null}resyncLiveState(){!this.destroyed&&this.liveStateSub&&this.startLiveState(this.loadGen)}onStreamEnded(e=!1,t){if(!this.destroyed){if((e||!this.rejoinEnabled())&&(this.cancelRejoin(),this.closeLiveState()),this.endedHandled){t===`match_ended`&&this._endedReason!==`match_ended`&&(this._endedReason=t,this.emit(`ended`,t),this.leavePipOnEnd());return}this.endedHandled=!0,this._endedReason=t??null,this.stopRefresh(),this.pendingStartLoad=!1,this.engine?.stop(),this.setState(`ended`),this.leavePipOnEnd()}}leavePipOnEnd(){this._endedReason===`interrupted`&&this.rejoinEnabled()||this.exitPictureInPicture().catch(()=>{})}get streamEnded(){return this._state===`ended`&&this.endedHandled}rejoinEnabled(){return this.opts.rejoinOnLive!==!1&&this.opts.liveStateEvents!==!1}scheduleRejoin(e){this.rejoinEnabled()&&!this.rejoinTimer&&(this.rejoinTimer=setTimeout(()=>{this.rejoinTimer=null,!(this.destroyed||e!==this.loadGen||this._state!==`ended`)&&this.rejoin()},Math.random()*R_))}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),v_(n,this.opts.theme),this.container=n,this.controlBar=A_({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,offlineMessage:this.opts.offlineMessage,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??V_);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!==U_||e.error.httpStatus!==403||e.error.code!==`FORBIDDEN`||e.error.serverCode===`license_refused`?!1:fh(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||fh(this._descriptor?.drm?.widevine?.licenseUrl)&&this.refreshLicense()},document.addEventListener(`visibilitychange`,this.onRefocus));let e=this.opts.licenseRefreshMs??H_;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()??zm}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.connectivity?.destroy(),this.connectivity=null,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.failedWhileOffline=!Lm(),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 X_(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 Z_=/^[A-Za-z0-9:_.-]{1,128}$/;function Q_(e){if(typeof e==`boolean`)return e;if(typeof e==`object`&&e){let t=e.endpoint;return typeof t==`string`?{endpoint:t}:{}}}function $_(){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:Q_(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 ev(){let e=$_();nv();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`}),tv(t,e)})},s=async n=>{i?.destroy(),i=null;try{let r=await q_({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`&&Z_.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 tv(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 nv(){let e=document.createElement(`style`);e.textContent=`html,body{margin:0;height:100%;background:#000;overflow:hidden}body{display:flex}`,document.head.appendChild(e)}return e.LiveStateHttpError=xe,e.ODDIN_THEME=g_,e.PlaybackError=a,e.applyTheme=v_,e.baseUrlForEnv=ht,e.bootEmbed=ev,e.clearDeviceId=Oe,e.clearRememberedBandwidth=Ve,e.createPlayer=q_,e.deriveEventsBaseUrl=we,e.detectDrmSupport=dt,e.enterVideoFullscreen=de,e.exitVideoFullscreen=fe,e.fetchCatalog=pe,e.fetchTournament=he,e.flattenMatches=_e,e.fullscreenSupported=ue,e.getDeviceId=De,e.isLowLatencyManifest=pt,e.isOddinMessage=Y_,e.licenseRequestHeaders=Ae,e.mountEmbed=X_,e.pollToLive=N,e.resolveStream=te,e.subscribeLiveState=Ce,e.videoFullscreenActive=le,e.watchStatus=ye,e})({});
|
|
174
|
+
`,E_=new WeakMap;function D_(e=document,t){let n=e.querySelector(`style#${w_}`);if(n&&(!t||E_.get(n)===t))return;let r=e.createElement(`style`);r.id=w_,t&&(r.nonce=t,r.setAttribute(`nonce`,t)),r.textContent=T_,E_.set(r,t),n?n.replaceWith(r):e.head.appendChild(r)}var O_={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 k_(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${O_[e]}</svg>`}var A_=3e3,j_=250,M_=new Set([`GONE`,`NOT_FOUND`,`GEO_DENIED`,`INVALID_URN`,`UNAUTHORIZED`,`DRM_DEVICE_REVOKED`]);function N_(e){let t=`This match isn't available in your country`;return e?`${t} (${e})`:t}var P_=`This device can't play protected video`;function F_(e){return`This browser can't play protected video. Allow protected content in its site settings, or use ${e?`Chrome, Edge or Safari`:`Chrome or Edge`} (Firefox asks when you retry)`}var I_=`Protected video can't be shown on this display. Use the built-in screen, or an HDCP-capable monitor and cable`;function L_(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,`offlineMessage`,void 0),i(this,`hideTimer`,void 0),i(this,`tapTimer`,void 0),i(this,`surfacePointerType`,``),i(this,`surfaceWasHidden`,!1),i(this,`pointerClosedMenu`,!1),i(this,`openMenu`,null),i(this,`scrubbing`,!1),i(this,`offFns`,[]),this.root=e.root,this.video=e.video,this.player=e.player,this.doc=e.root.ownerDocument??document,this.autoHideMs=e.autoHideMs??A_,this.logoUrl=e.logoUrl,this.statusOverlays=e.statusOverlays!==!1,this.streamEnded=e.streamEnded??(()=>!1),this.endedMessage=e.endedMessage??`This stream has ended`,this.interruptedMessage=e.interruptedMessage??`Reconnecting — please stand by`,this.errorMessage=e.errorMessage,this.offlineMessage=e.offlineMessage??`No internet connection — waiting to reconnect`,D_(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=k_(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=k_(`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=k_(`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(`offline`,()=>this.syncState())),this.offFns.push(this.player.on(`online`,()=>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)},j_)}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()}isGone(){return this.player.state===`error`&&this.lastError?.code===`GONE`}syncStatus(e){let t=null;if(this.statusOverlays){let n=e===`ended`||this.isGone(),r=this.player.offline&&!n&&e!==`idle`,i=!this.hasPlayed&&(e===`paused`||e===`waiting`);n?t=`ended`:r&&!i?t=`offline`:e===`error`?t=`error`:e===`waiting`?t=`waiting`:!this.hasPlayed&&(e===`idle`||e===`paused`)&&(t=`preplay`)}this.renderStatus(t)}statusMessageFor(e){if(e===`ended`)return this.isGone()?this.endedMessage:this.player.endedReason===`interrupted`?this.interruptedMessage:this.endedMessage;if(e===`offline`)return this.offlineMessage;if(e===`waiting`)return this.hasPlayed?`Reconnecting — please stand by`:`Starting soon…`;if(e===`error`){if(this.errorMessage!==void 0)return this.errorMessage;if(this.lastError?.code===`GEO_DENIED`)return N_(this.lastError.country);if(this.lastError?.code===`DRM_DEVICE_REVOKED`)return P_;if(this.lastError?.code===`DRM_CLIENT`){if(this.lastError.detail===`keySystemNoAccess`)return F_(!!this.player.descriptor?.drm?.fairplay?.licenseUrl);if(this.lastError.detail===`keySystemStatusOutputRestricted`)return I_}return this.lastError?.message??`Playback unavailable`}return 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=k_(`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&&!M_.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${k_(`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=`${z_(this.video.currentTime)} / ${z_(this.video.duration)}`)}syncLive(){let e=this.player.getStats(),t=e.isLive!==!1,n=this.isGone(),r=this.player.state===`ended`||n,i=!t&&!this.streamEnded()&&!n;this.live.style.display=t&&!r?``:`none`,this.time.style.display=i?``:`none`,this.seek.style.display=i?``:`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(B_(n),t===n.index,()=>this.player.setQuality(n.index)))}renderAudioMenu(){let e=this.player.getAudioTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Audio`,this.menu.replaceChildren(t);for(let t of e)this.menu.append(this.menuItem(V_(t),t.default,()=>this.player.setAudioTrack(t.id)))}renderCcMenu(){let e=this.player.getTextTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Subtitles`,this.menu.replaceChildren(t,this.menuItem(`Off`,!1,()=>this.player.setTextTrack(-1)));for(let t of e)this.menu.append(this.menuItem(H_(t),!1,()=>this.player.setTextTrack(t.id)))}onTracksChanged(){this.openMenu&&this.renderMenu(this.openMenu)}refreshTracks(){let e=this.player.getQualityLevels(),t=this.player.getAudioTracks(),n=this.player.getTextTracks();this.qualityBtn.style.display=e.length>1?``:`none`,this.audioBtn.style.display=t.length>1?``:`none`,this.ccBtn.style.display=n.length>0?``:`none`,this.onTracksChanged()}pipSupported(){return`pictureInPictureEnabled`in this.doc&&typeof this.video.requestPictureInPicture==`function`}async togglePip(){this.doc.pictureInPictureElement===this.video?await this.player.exitPictureInPicture():await this.player.enterPictureInPicture()}syncPip(e){this.pipBtn.setAttribute(`aria-pressed`,e?`true`:`false`)}async toggleFullscreen(){try{le(this.video,this.root)?await fe(this.video,this.root):await de(this.video,this.root)}catch{}}syncFullscreenSupport(){this.fsSupported=ue(this.video,this.root),this.fsBtn.style.display=this.fsSupported?``:`none`}syncFullscreen(){let e=le(this.video,this.root);this.setIcon(this.fsBtn,e?`fullscreenExit`:`fullscreen`),this.fsBtn.setAttribute(`aria-label`,e?`Exit fullscreen`:`Fullscreen`)}poke(){this.show(),this.scheduleHide()}show(){this.root.classList.remove(`havik-hide`)}scheduleHide(e=this.autoHideMs){this.hideTimer&&clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>this.hideIfIdle(),e)}hideIfIdle(){!this.video.paused&&!this.video.ended&&!this.openMenu&&!this.statusBox&&this.root.classList.add(`havik-hide`)}onDocPointer(e){this.pointerClosedMenu=!1,this.openMenu&&!this.menu.contains(e.target)&&([this.qualityBtn,this.audioBtn,this.ccBtn].some(t=>t.contains(e.target))||(this.closeMenu(),this.pointerClosedMenu=!0))}onKey(e){let t=e.target;if(!(t&&t!==this.root&&t!==this.seek&&t.tagName===`INPUT`)){switch(e.key){case` `:case`k`:this.togglePlay();break;case`m`:this.player.setMuted(!this.video.muted);break;case`f`:if(!this.fsSupported)return;this.toggleFullscreen();break;case`c`:this.ccBtn.style.display!==`none`&&this.toggleMenu(`cc`);break;case`l`:this.player.seekToLive();break;case`ArrowUp`:this.player.setVolume(Math.min(1,this.video.volume+.1));break;case`ArrowDown`:this.player.setVolume(Math.max(0,this.video.volume-.1));break;case`ArrowLeft`:this.nudge(-5);break;case`ArrowRight`:this.nudge(5);break;default:return}this.poke(),e.preventDefault()}}setIcon(e,t){e.innerHTML=k_(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 z_(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 B_(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function V_(e){return e.name||e.lang||`Track ${e.id}`}function H_(e){return e.name||e.lang||`Track ${e.id}`}var U_=6e3,W_=45e3,G_=2e3,K_=3,q_=6e4,J_=2,Y_=6e5,X_=5e3,Z_=2e3,Q_=48e4,$_=`keySystemLicenseRequestFailed`,ev=new Set([`GONE`,`NOT_FOUND`,`INVALID_URN`,`UNAUTHORIZED`,`GEO_DENIED`,`DRM_DEVICE_REVOKED`]);function tv(e){return!ev.has(e)}function nv(e){if(e.env!==void 0&&e.baseUrl!==void 0)throw new a(`INTERNAL`,0,`createPlayer: pass env OR baseUrl, not both (got env=${JSON.stringify(e.env)} and baseUrl=${JSON.stringify(e.baseUrl)})`);if(e.env!==void 0)return ht(e.env);if(!e.baseUrl)throw new a(`INTERNAL`,0,`createPlayer: env or baseUrl is required (env: 'integration' | 'production')`);return e.baseUrl}async function rv(e){if(!e.video||typeof e.video.play!=`function`)throw new a(`INTERNAL`,0,`createPlayer: opts.video must be an HTMLVideoElement`);let t=nv(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 iv({...e,baseUrl:t});return await n.start(),n}var iv=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,`liveStateLast`,null),i(this,`liveStateAliveAt`,0),i(this,`staleEndReloads`,0),i(this,`staleEndWindowAt`,0),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),i(this,`connectivity`,null),i(this,`failedWhileOffline`,!1),this.opts=e}get state(){return this._state}get offline(){return!Lm()}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.watchConnectivity(),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 this.destroy(),t}}resolveOptions(){return{baseUrl:this.opts.baseUrl,matchUrn:this.opts.matchUrn,credential:this.opts.credential,signal:this.abort.signal,apiHeaders:this.opts.apiHeaders}}beginArming(e,t,n=!1){let r=this.opts.liveStateEvents===!1?void 0:this.opts.eventsBaseUrl??we(this.opts.baseUrl);r?this.armWithSse(e,r,t,n):this.beginArmingByPolling(e)}beginArmingByPolling(e){te({...this.resolveOptions(),signal:this.abort.signal,waitForLive:this.buildWaitConfig(e)}).then(t=>{if(!(this.destroyed||this.abort.signal.aborted||e!==this.loadGen))return this.onResolved(t,e)}).catch(t=>{this.destroyed||this.abort.signal.aborted||e!==this.loadGen||this.fail(t instanceof a?t:new a(`INTERNAL`,0,String(t)))})}armWithSse(e,t,n,r=!1){let i=!1,o=!1,s=new AbortController;this.armFallbackCtrl=s,this.setState(`waiting`);let c=this.opts.waitForLive,l=c&&c!==!0?c.kickoffAt:void 0,d=typeof l==`number`?l:typeof l==`string`?Date.parse(l):NaN,f=n??(Number.isFinite(d)?d:void 0);setTimeout(()=>{i||this.destroyed||e!==this.loadGen||this.emit(`waiting`,{phase:r?`unavailable`:`tooEarly`,retryInMs:W_,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)};_(U_),this.armingSub=Ce({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>_(W_),onState:e=>{i||p()||(e.state===`live`||e.state===`gone`)&&setTimeout(g,Math.random()*G_)},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=qm(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}=p_(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 m_({endpoint:o,sid:r,player:t.name===`native`?`PLAYER_SAFARI_NATIVE`:`PLAYER_HLSJS`,sdkVersion:b_,environment:v_(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()??zm,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()),y_().then(e=>l.noteEnvironment(e)),this.opts.autoplay===!1&&l.noteAutoplay(`AUTOPLAY_RESULT_NOT_ATTEMPTED`)}currentPresentation(){let e=this.opts.video;if(typeof document<`u`&&document.pictureInPictureElement===e)return`pip`;let t=typeof document<`u`?document.fullscreenElement:null;return e.webkitDisplayingFullscreen===!0||t&&(t===e||t.contains(e))?`fullscreen`:`inline`}createEngine(e,t,n=!1){let r={...this.opts.hlsConfig};this.opts.startLevel!=null&&(r.startLevel=this.opts.startLevel),this.opts.liveLatencyTarget!=null&&(r.liveSyncDuration=this.opts.liveLatencyTarget);let i={video:this.opts.video,descriptor:e,credential:t,deviceId:De(),userId:this.opts.userId,lowLatency:this.opts.lowLatency===void 0||this.opts.lowLatency===`auto`||this.opts.lowLatency,snapToLiveOnRefocus:this.opts.snapToLiveOnRefocus,rememberBandwidth:this.opts.rememberBandwidth,sizeCapHeadroom:this.opts.sizeCapHeadroom,adaptiveHoldBack:this.opts.adaptiveHoldBack,adaptiveHoldBackCeiling:this.opts.adaptiveHoldBackCeiling,stallCap:this.opts.stallCap,stuckReload:this.opts.stuckReload,mediaDuringKey:this.opts.mediaDuringKey,preloadHints:this.opts.preloadHints,debug:this.opts.debug,deferLoad:n,hlsConfig:r,emit:e=>this.onEngineEvent(e),freshLicenseUrl:()=>this.refreshLicense()},o=this.opts.engine??`auto`;if(o===`native`)return new ph(i);if(o===`hls`)return new Kg(i);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&uh(this.opts.video)&&dh()||!e.drmEnabled&&fh()&&uh(this.opts.video))return new ph(i);if(Nh())return new Kg(i);if(uh(this.opts.video))return new ph(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`:if(e.reason===`stalled`&&this.reloadStaleEnd())break;this.onStreamEnded();break;case`error`:{let t=e.fatal&&this.isStaleLicenseDenial(e);if(this.analyticsSession?.noteError(e.error.code,e.error.message,e.fatal&&!t,e.error.httpStatus??0,Math.round(this.opts.video.currentTime*1e3),e.detail),t){this.staleLicenseReloaded=!0;let t=this.loadGen;this.emit(`warning`,e.error),Promise.resolve().then(()=>{if(!(this.destroyed||t!==this.loadGen)&&this._state!==`error`&&this._state!==`ended`)return this.reload().catch(()=>void 0)})}else e.fatal?this.fail(e.error):this.emit(`warning`,e.error);break}}}startLiveState(e){if(this.opts.liveStateEvents===!1)return;let t=this.opts.eventsBaseUrl??we(this.opts.baseUrl);if(!t)return;this.closeLiveState(),this.liveStateLast=null,this.liveStateAliveAt=0;let n=0,r=!1;this.liveStateSub=Ce({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onState:t=>{this.destroyed||e!==this.loadGen||(this.liveStateLast=t.state,this.liveStateAliveAt=Date.now(),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,!this.destroyed&&e===this.loadGen&&(this.liveStateAliveAt=Date.now())},onError:i=>{if(!(this.destroyed||e!==this.loadGen||r)&&!this.endedHandled){if(i instanceof xe&&(i.terminal||i.status===404)){r=!0,this.emit(`warning`,new a(o(i.status),i.status,`live-state events answered HTTP ${i.status} for ${this.opts.matchUrn}: the match is `+(i.terminal?`gone, so the subscription stopped`:`not in the catalog (ended and dropped, or not listed yet), so it retries every 5 min`)+` — end-of-stream detection falls back to the HLS staleness watchdog.`));return}n+=1,n>=K_&&(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}reloadStaleEnd(){if(this.destroyed||this.endedHandled||this._state===`error`||this._state===`ended`)return!1;let e=Date.now();if(this.liveStateLast!==`live`||e-this.liveStateAliveAt>q_||(e-this.staleEndWindowAt>Y_&&(this.staleEndReloads=0,this.staleEndWindowAt=e),this.staleEndReloads>=J_))return!1;this.staleEndReloads+=1;let t=new a(`UNAVAILABLE`,0,`live playlist stopped advancing for 12 s while the match is live (live-state push heard ${Math.round((e-this.liveStateAliveAt)/1e3)} s ago): reloading instead of ending (${this.staleEndReloads} of ${J_} this window)`);this.analyticsSession?.noteError(t.code,t.message,!1,0,Math.round(this.opts.video.currentTime*1e3),`staleEndReload`);let n=this.loadGen;return this.emit(`warning`,t),Promise.resolve().then(()=>{if(!(this.destroyed||n!==this.loadGen)&&this._state!==`error`&&this._state!==`ended`)return this.reload().catch(()=>void 0)}),!0}watchConnectivity(){this.connectivity||(this.connectivity=Rm(),this.connectivity.onChange(e=>{if(this.destroyed)return;if(!e){this.emit(`offline`);return}if(this.emit(`online`),this._state!==`error`||!this._lastError)return;let t=this._lastError.code;tv(t)&&(t===`NETWORK`||this.failedWhileOffline)&&this.retry().catch(()=>void 0)}))}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>=X_&&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()*G_))}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),C_(n,this.opts.theme),this.container=n,this.controlBar=L_({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,offlineMessage:this.opts.offlineMessage,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??Z_);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!==$_||e.error.httpStatus!==403||e.error.code!==`FORBIDDEN`||e.error.serverCode===`license_refused`?!1:_h(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||_h(this._descriptor?.drm?.widevine?.licenseUrl)&&this.refreshLicense()},document.addEventListener(`visibilitychange`,this.onRefocus));let e=this.opts.licenseRefreshMs??Q_;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()??zm}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.connectivity?.destroy(),this.connectivity=null,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.failedWhileOffline=!Lm(),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 av(e){return!!e&&typeof e==`object`&&typeof e.type==`string`&&e.type.startsWith(`oddin:`)}function ov(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||!av(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 sv=/^[A-Za-z0-9:_.-]{1,128}$/;function cv(e){if(typeof e==`boolean`)return e;if(typeof e==`object`&&e){let t=e.endpoint;return typeof t==`string`?{endpoint:t}:{}}}function lv(){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:cv(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 uv(){let e=lv();fv();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`}),dv(t,e)})},s=async n=>{i?.destroy(),i=null;try{let r=await rv({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`&&sv.test(e.matchUrn)&&s(e.matchUrn);break;case`oddin:destroy`:c()}},u=e=>{n&&e.origin===n&&av(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 dv(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 fv(){let e=document.createElement(`style`);e.textContent=`html,body{margin:0;height:100%;background:#000;overflow:hidden}body{display:flex}`,document.head.appendChild(e)}return e.LiveStateHttpError=xe,e.ODDIN_THEME=x_,e.PlaybackError=a,e.applyTheme=C_,e.baseUrlForEnv=ht,e.bootEmbed=uv,e.clearDeviceId=Oe,e.clearRememberedBandwidth=Ve,e.createPlayer=rv,e.deriveEventsBaseUrl=we,e.detectDrmSupport=dt,e.enterVideoFullscreen=de,e.exitVideoFullscreen=fe,e.fetchCatalog=pe,e.fetchTournament=he,e.flattenMatches=_e,e.fullscreenSupported=ue,e.getDeviceId=De,e.isLowLatencyManifest=pt,e.isOddinMessage=av,e.licenseRequestHeaders=Ae,e.mountEmbed=ov,e.pollToLive=N,e.resolveStream=te,e.subscribeLiveState=Ce,e.videoFullscreenActive=le,e.watchStatus=ye,e})({});
|
|
175
175
|
//# sourceMappingURL=havik-player.global.js.map
|