@oddin-gg/havik-player 2.23.1 → 2.23.2
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 +1 -1
- package/dist/havik-player.global.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/embed/index.html +1 -1
- package/examples/vanilla.html +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("hls.js");c=s(c,1);var l=class extends Error{code;httpStatus;retryAfterMs;requestId;serverCode;liveStartsAtMs;country;constructor(e,t,n,r){super(n),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 u(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 d(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 f(e,t){return e===401?`UNAUTHORIZED`:e===403?t===`cdm_revoked`?`DRM_DEVICE_REVOKED`:`FORBIDDEN`:`DRM_CLIENT`}var p=new Set([`TOO_EARLY`,`UNAVAILABLE`,`RATE_LIMITED`,`NETWORK`]);function m(e){return p.has(e)}async function h(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 g(e){return e===`live`||e===`ended`||e===`upcoming`||e===`pending`?e:`upcoming`}function _(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`&&ee(n.logoUrl)&&(i.logoUrl=n.logoUrl),t.push(i)}return t.length>0?t:void 0}function ee(e){try{return new URL(e).protocol===`https:`}catch{return!1}}function v(e,t){let n=e.replace(/\/+$/,``),r;try{r=new URL(n+t)}catch{throw new l(`INTERNAL`,0,`invalid baseUrl: ${JSON.stringify(e)}`)}if(r.protocol!==`https:`&&r.protocol!==`http:`)throw new l(`INTERNAL`,0,`baseUrl must be http(s), got: ${JSON.stringify(e)}`);return r.toString()}function te(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 y(e,t){let n=await h(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 l(`ABORTED`,0,`request aborted`,{cause:e}):new l(`NETWORK`,0,`network request failed: ${ne(e)}`,{cause:e})}}function ne(e){return e instanceof Error?e.message:String(e)}var re=new Set;function b(e,t=e){re.has(t)||(re.add(t),console.warn(`havik-player: ${e}`))}var ie=1e3,ae=3e4,oe=6e5,se=3e5,ce=1e3,le={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function ue(e){let t=e===!0||e===!1?{}:e,n=Math.max(ce,t.floorMs??ie),r=Math.max(n,t.ceilMs??ae),i=Math.max(0,t.imminentMs??oe),a=Math.max(r,t.sanityFloorMs??se);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:de(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function de(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 fe(e,t,n){return Math.min(n,Math.max(t,e))}function pe(e){return Math.round(e*(1+.15*Math.random()))}function me(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:fe(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 he(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new l(`ABORTED`,0,`wait-for-live aborted`));return}let i=()=>{clearTimeout(a),r(new l(`ABORTED`,0,`wait-for-live aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}async function ge(e,t,n){let r=ue(t),i=Date.now(),a=r.timeoutMs==null?1/0:i+r.timeoutMs,o=0,s;for(;;){if(n?.aborted)throw new l(`ABORTED`,0,`wait-for-live aborted`);try{return await e()}catch(e){if(!(e instanceof l)||!m(e.code))throw e;o+=1,e.liveStartsAtMs!=null&&Number.isFinite(e.liveStartsAtMs)&&(s=e.liveStartsAtMs);let t=Date.now(),c=me(e.retryAfterMs,t,r,s),u=c.ttkMs,d=c.delay;if(r.jitter&&(d=pe(d)),t+d>a)throw new l(`TIMEOUT`,e.httpStatus,`timed out after ${r.timeoutMs}ms waiting for the stream to go live`,{retryAfterMs:e.retryAfterMs,cause:e});r.onState?.({phase:le[e.code]??`unavailable`,retryInMs:d,attempt:o,elapsedMs:t-i,ttkMs:u}),await he(d,n)}}}async function x(e){if(!e.matchUrn||typeof e.matchUrn!=`string`)throw new l(`INVALID_URN`,0,`resolveStream: a non-empty matchUrn is required`);let t=await y(v(e.baseUrl,`/v1/playback/${encodeURIComponent(e.matchUrn)}`),{credential:e.credential,signal:e.signal,apiHeaders:e.apiHeaders});if(!t.ok)throw await _e(t);return be(await t.json(),e.matchUrn)}function S(e){let t=()=>x(e);return e.waitForLive?ge(t,e.waitForLive,e.signal):t()}async function _e(e){let t=te(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,a,o;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)&&(a=e)}e.status===451&&typeof t?.country==`string`&&/^[A-Z]{2}$/.test(t.country)&&(o=t.country)}catch{}return new l(u(e.status),e.status,r,{retryAfterMs:t,requestId:n,serverCode:i,liveStartsAtMs:a,country:o})}var ve=new Set([`matchUrn`,`protocol`,`drmEnabled`,`manifestUrl`,`drm`,`serverTime`,`liveStartsAt`,`expiresAt`,`analytics`]);function C(e,t){let n;try{n=new URL(t)}catch{throw new l(`INTERNAL`,0,`playback ${e} is not a valid URL`)}if(n.protocol!==`https:`&&n.protocol!==`http:`)throw new l(`INTERNAL`,0,`playback ${e} has a disallowed scheme: ${n.protocol}`);return t}function ye(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 be(e,t){if(!e.manifestUrl)throw new l(`INTERNAL`,0,`playback response is missing manifestUrl`);let n=e.drmEnabled??!!e.drm,r={matchUrn:e.matchUrn??t,protocol:`hls`,drmEnabled:n,manifestUrl:C(`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=ye(e.analytics.endpoint);t&&(r.analytics.endpoint=t)}if(n&&e.drm){let t={};e.drm.widevine?.licenseUrl&&(t.widevine={licenseUrl:C(`widevine licenseUrl`,e.drm.widevine.licenseUrl)}),e.drm.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&(t.fairplay={licenseUrl:C(`fairplay licenseUrl`,e.drm.fairplay.licenseUrl),certificateUrl:C(`fairplay certificateUrl`,e.drm.fairplay.certificateUrl)}),(t.widevine||t.fairplay)&&(r.drm=t)}let i={};for(let[t,n]of Object.entries(e))ve.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}function w(e){return e.ownerDocument??document}function xe(e){return e.fullscreenElement??e.webkitFullscreenElement??null}function T(e,t){let n=xe(w(e));return n!=null&&(n===e||t!=null&&n===t)||e.webkitDisplayingFullscreen===!0}function E(e,t){let n=t??e,r=w(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 D(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 O(e,t){let n=e;if(n.webkitDisplayingFullscreen){n.webkitExitFullscreen?.();return}let r=w(e),i=xe(r);i!=null&&(i===e||t!=null&&i===t)&&(typeof r.exitFullscreen==`function`?await r.exitFullscreen():r.webkitExitFullscreen?.())}async function Se(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=v(e.baseUrl,`/v1/catalog`+(n?`?${n}`:``)),i=new Headers;e.etag&&i.set(`If-None-Match`,e.etag);let a=await y(r,{credential:e.credential,signal:e.signal,headers:i,apiHeaders:e.apiHeaders});if(a.status===304)return{tournaments:[],etag:e.etag,notModified:!0};if(!a.ok)throw new l(u(a.status),a.status,`catalog request failed (HTTP ${a.status})`);return{tournaments:Ce(await a.json()),etag:a.headers.get(`etag`)??void 0,notModified:!1}}function Ce(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:g(e.status),statusRaw:e.status,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r,teams:_(e.teams)}))}})}async function we(e){let t=v(e.baseUrl,`/v1/tournaments/${encodeURIComponent(e.urn)}`),n=new Headers;e.etag&&n.set(`If-None-Match`,e.etag);let r=await y(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 l(u(r.status),r.status,`tournament request failed (HTTP ${r.status})`);return{tournament:Te(await r.json()),etag:r.headers.get(`etag`)??void 0,notModified:!1,notFound:!1}}function Te(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:g(e.status),statusRaw:e.status,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r,teams:_(e.teams)}))}}function Ee(e){return e.tournaments.flatMap(e=>e.matches)}var De=new Set([`NOT_FOUND`,`GEO_DENIED`,`GONE`,`INVALID_URN`]);function Oe(e){let t=Math.max(2e3,e.intervalMs??1e4),n=new AbortController,r,i,a,o=!1,s=()=>{o||(r=setTimeout(c,t))},c=async()=>{try{let t=v(e.baseUrl,`/v1/matches/${encodeURIComponent(e.matchUrn)}`),r=new Headers;i&&r.set(`If-None-Match`,i);let o=await y(t,{credential:e.credential,signal:n.signal,headers:r,apiHeaders:e.apiHeaders});if(o.status!==304){if(!o.ok)throw new l(u(o.status),o.status,`match status request failed (HTTP ${o.status})`);i=o.headers.get(`etag`)??i;let t=await o.json(),n=g(t.status),r=typeof t.status==`string`?t.status:n,s=_(t.teams),c=JSON.stringify([r,t.datePlannedStart??null,s??null]);c!==a&&(a=c,e.onChange({matchUrn:t.matchUrn??e.matchUrn,matchName:t.matchName,status:n,statusRaw:t.status,datePlannedStart:t.datePlannedStart,teams:s}))}}catch(t){if(!n.signal.aborted){let n=t instanceof l?t:new l(`NETWORK`,0,String(t));De.has(n.code)&&(o=!0),e.onError?.(n)}}finally{s()}};return c(),{stop(){o=!0,n.abort(),r&&clearTimeout(r)}}}var ke=45e3;function k(e){let t=Math.max(250,e.minBackoffMs??1e3),n=Math.max(t,e.maxBackoffMs??15e3),r=e.idleTimeoutMs??ke,i=Number.isFinite(r)&&r>0?r:0,a=new AbortController,o=!1,s=e=>new Promise(t=>{if(a.signal.aborted)return t();let n=setTimeout(t,e);a.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),c=t=>{if(o)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
|
-
`));t&&typeof t.state==`string`&&e.onState(t)}catch{}},l=/\r\n\r\n|\n\n|\r\r/,u=async(e,t,n)=>{let r=e.getReader(),a=new TextDecoder,s=``,u=!1,d,f=()=>{i&&(clearTimeout(d),d=setTimeout(()=>{n(),r.cancel().catch(()=>{})},i))};try{for(f();;){let{value:e,done:n}=await r.read();if(n)return;e&&e.length>0&&(f(),u||(u=!0,t())),s+=a.decode(e,{stream:!0});let i;for(;(i=l.exec(s))!==null;)c(s.slice(0,i.index)),s=s.slice(i.index+i[0].length);if(o)return}}finally{clearTimeout(d),await r.cancel().catch(()=>{})}};return(async()=>{let r=t;for(;!o;){let c=new AbortController,l=()=>c.abort();a.signal.addEventListener(`abort`,l,{once:!0});let d=null,f,p=()=>{d=`no data for ${i}ms`,c.abort()};try{let n=await h(e.credential);if(o)return;let a=v(e.eventsBaseUrl,`/v1/events/${encodeURIComponent(e.matchUrn)}`);i&&(f=setTimeout(()=>{d=`no response headers within ${i}ms`,c.abort()},i));let s=await fetch(a,{method:`GET`,headers:{"x-api-key":n.apiKey,accept:`text/event-stream`},signal:c.signal,cache:`no-store`,credentials:`omit`,mode:`cors`});if(clearTimeout(f),o)return;!s.ok||!s.body?e.onError?.(Error(`live-state subscribe failed: HTTP ${s.status}`)):await u(s.body,()=>{r=t},p)}catch(t){if(o||a.signal.aborted)return;d||e.onError?.(t)}finally{clearTimeout(f),a.signal.removeEventListener(`abort`,l),c.abort()}if(o)return;d&&e.onError?.(Error(`live-state subscribe idle: ${d} — reconnecting`)),await s(r),r=Math.min(n,r*2)}})(),{close(){o||(o=!0,a.abort())}}}function A(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var j=`havik.player.deviceId`,M;function N(){if(M)return M;try{let e=globalThis.localStorage?.getItem(j);if(e)return M=e,e}catch{}let e=je();M=e;try{globalThis.localStorage?.setItem(j,e)}catch{}return e}function Ae(){M=void 0;try{globalThis.localStorage?.removeItem(j)}catch{}}function je(){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 Me(e,t,n={}){let r={"x-api-key":t.apiKey,"X-Match-Urn":e.matchUrn,"X-Device-Id":n.deviceId??N(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var P=`havik.player.bandwidth`,Ne=.8,Pe=2e7,Fe=3e5;function Ie(){return globalThis.navigator?.connection}function Le(){let e=Ie()?.type;return typeof e==`string`&&e!==``&&e!==`unknown`?e:`any`}function Re(){let e=Ie()?.downlink;return typeof e==`number`&&Number.isFinite(e)&&e>0?e*1e6:void 0}function ze(){try{let e=globalThis.localStorage?.getItem(P);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function Be(e=Date.now()){let t=ze()[Le()];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=Re(),i=r===void 0?t.bps:Math.min(t.bps,r);return Math.round(Math.min(Pe,Math.max(Fe,i*Ne)))}function Ve(e,t=Date.now()){if(!Number.isFinite(e)||e<=0)return;let n=ze();n[Le()]={bps:Math.round(e),at:t};try{globalThis.localStorage?.setItem(P,JSON.stringify(n))}catch{}}function He(){try{globalThis.localStorage?.removeItem(P)}catch{}}var Ue=new WeakMap;function We(e,t){let n=Ue.get(e);n||(n=new Map,Ue.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 F(){return typeof navigator<`u`&&typeof navigator.requestMediaKeySystemAccess==`function`}var I=[`SW_SECURE_DECODE`,`SW_SECURE_CRYPTO`];function Ge(e){return e.startsWith(`com.widevine`)}function L(e,t){if(!Ge(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=I.indexOf(e.robustness);return n===-1||I.indexOf(t)>n})},r=I.flatMap(e=>t.filter(t=>n(t,e)).map(t=>({...t,videoCapabilities:t.videoCapabilities?.map(t=>({...t,robustness:e}))})));return[...t,...r]}function Ke(e){return(t,n)=>F()?navigator.requestMediaKeySystemAccess(t,L(t,n)).then(t=>({keySystem:t.keySystem,getConfiguration:()=>t.getConfiguration(),createMediaKeys:()=>We(e,t)})):Promise.reject(Error(`navigator.requestMediaKeySystemAccess is unavailable — EME needs a secure context (https, or localhost)`))}var R={video:`SW_SECURE_DECODE`,audio:`SW_SECURE_CRYPTO`,scheme:`cbcs`};function qe(e){if(!F())return;let t=(e,t)=>({contentType:e,robustness:t,encryptionScheme:R.scheme});Ke(e)(`com.widevine.alpha`,[{initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],audioCapabilities:[t(`audio/mp4; codecs="mp4a.40.2"`,R.audio)],videoCapabilities:[t(`video/mp4; codecs="avc1.42e01e"`,R.video)]}]).then(e=>e.createMediaKeys()).catch(()=>{})}function z(e){let t=B(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 B(e){return(e??``).trim().toLowerCase()}var Je={hevc:`hvc1.1.6.L93.90`,dv:`dvh1.05.06`,av1:`av01.0.05M.08`,vp9:`vp09.00.10.08`},Ye=new Map,V=new Map;function Xe(e){let t=B(e),n=Ye.get(t);if(n)return n;let r={initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],videoCapabilities:[{contentType:`video/mp4; codecs="${e.trim()}"`,robustness:R.video,encryptionScheme:R.scheme}]},i=(async()=>{try{return await navigator.requestMediaKeySystemAccess(`com.widevine.alpha`,L(`com.widevine.alpha`,[r])),!0}catch{return!1}})().then(e=>(V.set(t,e),e));return Ye.set(t,i),i}function Ze(){if(F())for(let e of Object.values(Je))Xe(e)}function Qe(e){let t=z(e);if(t)return t===`avc`?!0:V.get(B(e))??V.get(B(Je[t]))}var $e=5e3,et=`video/mp4; codecs="avc1.42E01E"`,tt=`audio/mp4; codecs="mp4a.40.2"`,nt={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function rt(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:et,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:tt,robustness:``,encryptionScheme:`cbcs`}]}]:L(`com.widevine.alpha`,[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:et,robustness:R.video,encryptionScheme:R.scheme}],audioCapabilities:[{contentType:tt,robustness:R.audio,encryptionScheme:R.scheme}]}])}function it(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 at(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??$e,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=nt[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 it((await it(i(n,rt(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 ot=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function st(e){return ot.test(e)}var ct={integration:`https://feed-dev.oddin-video.gg`,production:`https://feed.oddin-video.gg`};function lt(e){let t=Object.prototype.hasOwnProperty.call(ct,e)?ct[e]:void 0;if(!t)throw new l(`INTERNAL`,0,`unknown env ${JSON.stringify(e)} — expected 'integration' or 'production'`);return t}var ut={droppedFrames:0};function dt(e){try{return new URL(e).host}catch{return``}}var ft=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function pt(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`||ft.test(i.name))&&i.startTime>=n){let e=dt(i.name);e&&(t=e,n=i.startTime)}return t}function H(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var mt=class{video;baseFrames=0;baseDropped=0;lastFrames=0;lastDropped=0;constructor(e){this.video=e}read(){let e=H(this.video);return e.totalFrames<this.lastFrames&&(this.baseFrames+=this.lastFrames),e.dropped<this.lastDropped&&(this.baseDropped+=this.lastDropped),this.lastFrames=e.totalFrames,this.lastDropped=e.dropped,{dropped:this.baseDropped+e.dropped,totalFrames:this.baseFrames+e.totalFrames}}attach(){let e=()=>void this.read();return this.video.addEventListener(`timeupdate`,e),this.video.addEventListener(`seeking`,e),()=>{this.video.removeEventListener(`timeupdate`,e),this.video.removeEventListener(`seeking`,e)}}};function ht(e,t){let n=[[`playing`,()=>t(`playing`)],[`waiting`,()=>t(`buffering`)],[`stalled`,()=>t(`buffering`)],[`pause`,()=>{e.ended||t(`paused`)}],[`ended`,()=>t(`ended`)]];for(let[t,r]of n)e.addEventListener(t,r);return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}var gt=2e3,_t=3,U=500,vt=6e3,yt=.25,bt=250,xt=.05,St=4,Ct=12e3,wt=.25,Tt=1e3;function Et(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 W(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function G(){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 Dt(){if(typeof navigator>`u`||!G())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var K=class{name=`native`;deps;onLoaded;onError;onEncrypted;fairplayLicenseUrl;keySession=null;fairplayArmed=!1;onVisibility=null;onPageShow=null;hiddenSince=null;refocusTimer=null;edgeTimer=null;onEdgeReset=null;lastBufferedEnd=null;bufferedAdvancedAt=null;lastSeekableEnd=null;edgeStampedAt=null;lastTickAt=null;endedEmitted=!1;fairplayKeyIV;loadStarted;preloadTouched=!1;savedPreload=null;cdnHost=``;builtAt;frameCounter;detachFrames=null;constructor(e){this.deps=e,this.frameCounter=new mt(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 l(`DRM_CLIENT`,0,`native HLS engine cannot satisfy this DRM (Widevine requires the hls.js engine); use engine "auto"/"hls" on a Widevine-capable browser`),fatal:!0});return}this.armFairPlay()}let r=!this.loadStarted;this.onLoaded=r?void 0:()=>n({type:`ready`}),this.onError=()=>n({type:`error`,error:new l(`INTERNAL`,0,`native HLS playback error`),fatal:!0}),this.onLoaded&&e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=kt(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:a}=this.deps,o=t.drm?.fairplay;if(!o)return;this.fairplayLicenseUrl=o.licenseUrl;let s=(e,t,n,r)=>a({type:`error`,error:new l(f(t,r),t,e,r?{serverCode:r}:void 0),fatal:n}),c=async e=>{try{return await e.text()}catch{return``}};this.onEncrypted=a=>{let l=a;l.initData&&!this.fairplayArmed&&(this.fairplayArmed=!0,this.fairplayKeyIV=Et(l.initData),(async()=>{try{let a=await(await navigator.requestMediaKeySystemAccess(`com.apple.fps`,[{initDataTypes:[l.initDataType],videoCapabilities:[{contentType:`application/vnd.apple.mpegurl`,robustness:``}],distinctiveIdentifier:`not-allowed`,persistentState:`not-allowed`,sessionTypes:[`temporary`]}])).createMediaKeys(),u=await fetch(o.certificateUrl,{headers:{"x-api-key":n.apiKey}});if(!u.ok){this.fairplayArmed=!1,s(`FairPlay certificate request failed: ${u.status}`,u.status,!0);return}await a.setServerCertificate(await u.arrayBuffer()),await e.setMediaKeys(a);let f=a.createSession();this.keySession=f,f.addEventListener(`message`,e=>{(async()=>{try{let a=await fetch(this.fairplayLicenseUrl??o.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?d(await c(a)):void 0;s(`FairPlay license request failed: ${a.status}`,a.status,!0,e);return}await f.update(new Uint8Array(await a.arrayBuffer()))}catch(e){s(`FairPlay license request failed: ${String(e)}`,0,!0)}})()}),await f.generateRequest(l.initDataType,l.initData)}catch(e){this.fairplayArmed=!1,s(`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||=pt(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<=St,!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=q();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=gt&&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=q,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=U;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+yt),s=Math.max(r,t()-n)>=vt;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,U)};this.refocusTimer=setTimeout(i,U)}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=Ot(e,e.currentTime);t!=null&&((this.lastBufferedEnd==null||Math.abs(t-this.lastBufferedEnd)>=xt)&&(this.bufferedAdvancedAt=q()),this.lastBufferedEnd=t)},bt)}checkEndStale(){if(this.endedEmitted)return;let e=q(),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)>=wt;this.lastSeekableEnd=n;let i=this.deps.video,a=typeof document<`u`&&document.visibilityState===`hidden`;if(r||t>Tt||a||i.paused){this.edgeStampedAt=e;return}e-(this.edgeStampedAt??e)>Ct&&(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=Ot(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,(q()-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-_t,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 q(){return typeof performance<`u`?performance.now():Date.now()}function Ot(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 kt(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function J(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 At=4096;function jt(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>At))try{return new TextDecoder().decode(n)}catch{return}}var Mt=15e3,Nt=5e3,Pt=6;function Ft(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var It=class{cmcd;entries=new Map;keyed=new Set;perTrack=new Map;stats={started:0,served:0,missed:0,failed:0,expired:0};constructor(e={}){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=Ft(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;if(i>=Pt)return;this.perTrack.set(t,i+1);let a=new AbortController,o={started:performance.now(),first:0,bytes:Promise.resolve(null),abort:a};o.bytes=fetch(this.withCmcd(e,t,n),{credentials:`omit`,mode:`cors`,signal:a.signal}).then(async e=>(o.first=performance.now(),e.ok?e.arrayBuffer():null)).catch(()=>null),this.entries.set(r,o),this.stats.started+=1,setTimeout(()=>{this.entries.get(r)===o&&(this.entries.delete(r),a.abort(),this.stats.expired+=1)},Mt)}take(e){let t=Ft(e),n=this.entries.get(t);return n&&this.entries.delete(t),n}destroy(){for(let e of this.entries.values())e.abort.abort();this.entries.clear()}withCmcd(e,t,n){let{sessionId:r,contentId:i}=this.cmcd;if(!r&&!i)return e;let a=[];i&&a.push(`cid="${i}"`),a.push(`ot=${n===`init`?`i`:t===`audio`?`a`:`v`}`),a.push(`sf=h`),r&&a.push(`sid="${r}"`),a.push(`st=ll`);try{let t=new URL(e);return t.searchParams.set(`CMCD`,a.join(`,`)),t.toString()}catch{return e}}};function Lt(e){let t=c.default.DefaultConfig?.loader;if(typeof t!=`function`)return;class n extends t{served=!1;cancelled=!1;stats=Rt();load(t,n,r){let i=t.rangeEnd?void 0:e.take(t.url);if(!i){super.load(t,n,r);return}this.served=!0;let a=performance.now(),o=n?.loadPolicy?.maxTimeToFirstByteMs||Nt,s=setTimeout(()=>{!this.cancelled&&this.served&&(i.abort.abort(),e.stats.failed+=1,this.served=!1,super.load(t,n,r))},o);i.bytes.then(o=>{if(clearTimeout(s),this.cancelled||!this.served)return;if(!o){e.stats.failed+=1,this.served=!1,super.load(t,n,r);return}e.stats.served+=1;let c=this.stats;c.loading.start=a,c.loading.first=Math.max(a,i.first||a),c.loading.end=performance.now(),c.loaded=c.total=o.byteLength,r.onSuccess({url:t.url,data:o},c,t,null)})}abort(){if(this.served){this.cancelled=!0,this.stats.aborted=!0;return}super.abort()}}return n}function Rt(){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 zt(e){return e===`audio`?`audio`:`main`}function Bt(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 Y(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}function Vt(){return c.default.isSupported()}var Ht=1e6,Ut=20,Wt=1e4,Gt=3,Kt=5,qt=3,Jt=1e4,Yt=3e4,Xt=12e3,Zt=3e3,Qt=.02,$t=6e3,en=.5,tn=3,nn=.5,rn=1.1,an=.25,on=5e3,sn=4e3,cn=2,ln=5,un=2,dn=2,fn=4,pn=4,mn=2e3,hn=3e4,gn=1,_n=2;function vn(e,t,n){if(n<=0||t<0||t>=e.length)return t;let r=(t,n)=>e[t].width===e[n].width&&e[t].height===e[n].height,i=t=>{for(;t+1<e.length&&r(t+1,t);)t++;return t},a=i(t);for(let t=0;t<n&&a+1<e.length;t++)a=i(a+1);return a}var yn=.2,bn=30,xn=2,Sn=2,Cn=2,wn=9,Tn=.5,En=64,Dn=1e4,On=8,kn=.6,An=.4,jn=.4,Mn=2,Nn=6e4,X=.5,Pn=3.5,Fn=300;function In(){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 Ln(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Cn;let t=Math.max(12,e.liveSyncDuration+wn);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),Rn(e,e.liveSyncDuration)}function Rn(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 zn=class{name=`hls`;hls=null;deps;licenseUrl;detectedLowLatency=!1;bytesLoaded=0;prefetch=null;reportedFirstPlaylist=!1;reportedFirstBytes=!1;reportedDrmReady=!1;playlistBytesLoaded=0;renditionSwitches=0;licenseTimeMs=0;licenseRequested=!1;upshifts=0;downshifts=0;lastLevelIndex=-1;requestCount=0;requestErrors=0;requestTimesMs=[];cdnHost=``;ladderHeights;ladderTopBitrateKbps=0;mediaRecoveries=0;networkRecoveries=0;licenseRecoveries=0;recoveryResetTimer=null;networkRetryTimer=null;licenseRetryTimer=null;onVisibility=null;onSeeking=null;onPause=null;onPlay=null;pauseSuspendTimer=null;loadSuspended=!1;stopped=!1;sawLive=!1;lastEndSN=-1;lastAdvanceMs=0;endWatchdog=null;endedEmitted=!1;lastFragLoadingMs=0;starvedTicks=0;starvationKicks=0;kickPending=!1;kickTicks=0;starvationRebuilds=0;kickKind=null;starvedFrames=0;deadTicks=0;mainFragsSinceTick=0;bwFragsLoaded=0;bwSavedAt=0;recentMainFrags=[];chaseSuspended=!1;savedLiveMaxLatency;savedMaxSyncRate;chaseLatency=-1;catchUpRate=1;catchUpEngaged=!1;onTimeUpdate=null;chaseTicks=0;liveRetargets=0;holdBackEnabled;holdBackSamples=[];holdBackBase=-1;holdBackStepCount=0;holdBackApplied=0;holdBackSlowTicks=0;holdBackFastSince=0;holdBackSteps=0;holdBackPriorChecked=!1;capObserver=null;capTimer=null;sizeCapLevel=null;bitrateCapLevel=-1;pushedCapLevel=-1;pushedCapReason=null;fpsCapBitrate=null;fpsCapFailedHeight=null;fpsCapManaged=!0;fpsLastFrames=-1;fpsLastDropped=-1;fpsBadTicks=0;fpsGraceTicks=0;fpsDownCaps=0;sizeCapManaged=!0;dprMedia=null;onDprChange=null;loadStarted;frameCounter;detachFrames=null;constructor(e){this.deps=e,this.holdBackEnabled=e.adaptiveHoldBack!==!1,this.frameCounter=new mt(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=W(n)&&G(),a=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!a){r({type:`error`,error:new l(`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&&a&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&(qe(n),Ze()),this.startHls(),t!==!1&&typeof document<`u`&&(this.onVisibility=()=>{let e=this.hls;if(document.visibilityState!==`visible`||!e)return;let t=e.liveSyncPosition;if(typeof t!=`number`)return;let r=typeof e.targetLatency==`number`&&e.targetLatency>0?e.targetLatency:3;t-n.currentTime>Math.max(r*3,8)&&(n.currentTime=t)},document.addEventListener(`visibilitychange`,this.onVisibility)),this.onSeeking=()=>{this.clampOverSeek(),this.loadSuspended&&(this.resumeLoading(),this.schedulePauseSuspend())},n.addEventListener(`seeking`,this.onSeeking),this.onTimeUpdate=()=>this.updateCatchUpBand(),n.addEventListener(`timeupdate`,this.onTimeUpdate),this.onPause=()=>this.schedulePauseSuspend(),this.onPlay=()=>this.resumeLoading(),n.addEventListener(`pause`,this.onPause),n.addEventListener(`play`,this.onPlay),this.sizeCapManaged&&typeof ResizeObserver<`u`&&(this.capObserver=new ResizeObserver(()=>this.onMediaResize()),this.capObserver.observe(n),this.watchDprChanges())}schedulePauseSuspend(){this.pauseSuspendTimer||this.loadSuspended||this.stopped||!this.loadStarted||(this.pauseSuspendTimer=setTimeout(()=>{this.pauseSuspendTimer=null;let{video:e}=this.deps;if(e.paused&&!e.ended&&!this.stopped&&this.hls){try{this.hls.stopLoad()}catch{return}this.loadSuspended=!0}},on))}resumeLoading(){if(this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.resetChaseWindow(),this.resetFrameDropWindow(),this.loadSuspended&&(this.loadSuspended=!1,!this.stopped&&this.hls)){this.lastAdvanceMs=Date.now(),this.lastFragLoadingMs=0,this.resetStarvationWindow(),this.resetChaseWindow(),this.clearKick();try{this.hls.startLoad(-1)}catch{}}}startLoad(){this.loadStarted||(this.loadStarted=!0,this.deps.video.paused&&this.schedulePauseSuspend(),this.hls?.startLoad(-1))}watchDprChanges(){if(typeof matchMedia!=`function`)return;this.unwatchDprChanges();let e=typeof self<`u`&&self.devicePixelRatio||1,t=matchMedia(`(resolution: ${e}dppx)`);if(typeof t.addEventListener!=`function`)return;let n=()=>{this.onMediaResize(),this.watchDprChanges()};t.addEventListener(`change`,n),this.dprMedia=t,this.onDprChange=n}unwatchDprChanges(){this.dprMedia&&this.onDprChange&&this.dprMedia.removeEventListener(`change`,this.onDprChange),this.dprMedia=null,this.onDprChange=null}clampOverSeek(){let e=this.hls;if(!e||this.chaseSuspended||(e.levels[e.currentLevel]??e.levels[e.loadLevel])?.details?.live!==!0)return;let t=e.liveSyncPosition;if(typeof t!=`number`||!Number.isFinite(t))return;let{video:n}=this.deps;n.currentTime<=t+Tn||(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)<Qt)){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:l}=this.deps;this.clearKick(),this.resetStarvationWindow(),this.resetChaseWindow(),this.resetFrameDropWindow(),this.lastFragLoadingMs=0,this.lastEndSN=-1,this.lastAdvanceMs=0;let u=t.drmEnabled&&!!(t.drm?.widevine?.licenseUrl||t.drm?.fairplay?.licenseUrl),d=W(this.deps.video)&&G(),f={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,liveDurationInfinity:!0,maxBufferHole:.5,maxLiveSyncPlaybackRate:d?1:1.1,abrEwmaDefaultEstimate:this.startEstimate(),capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...u?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:R.video,audioRobustness:R.audio,videoEncryptionScheme:R.scheme,audioEncryptionScheme:R.scheme},...F()?{requestMediaKeySystemAccessFunc:Ke(e)}:{},licenseXhrSetup:(e,a)=>{let o=performance.now(),s=()=>{e.open(`POST`,this.licenseUrl??a,!0),e.setRequestHeader(`x-api-key`,n.apiKey),e.setRequestHeader(`X-Match-Urn`,t.matchUrn),e.setRequestHeader(`X-Device-Id`,r),i&&e.setRequestHeader(`X-User-Id`,i),this.licenseRequested=!0,e.addEventListener(`loadend`,()=>{this.licenseTimeMs===0&&(this.licenseTimeMs=Math.max(1,Math.round(performance.now()-o)))})},{freshLicenseUrl:c}=this.deps;if(!c||!J(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),Jt)});return Promise.race([c().catch(()=>void 0),d]).finally(()=>clearTimeout(u)).then(e=>{if(!this.hls||this.hls!==l)throw Error(`havik-player: engine torn down during refresh`);e&&(this.licenseUrl=e),s()})}}:{},...t.analytics?.sid?{cmcd:{sessionId:t.analytics.sid,contentId:t.matchUrn,useHeaders:!1}}:{},...s};if(this.prefetch?.destroy(),this.prefetch=null,u&&this.deps.mediaDuringKey!==!1&&!f.fLoader){let e=new It({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=Lt(e);n&&(this.prefetch=e,f.fLoader=n)}Ln(f),this.catchUpRate=typeof f.maxLiveSyncPlaybackRate==`number`?f.maxLiveSyncPlaybackRate:1,this.catchUpEngaged=!1,this.catchUpRate>1&&(f.maxLiveSyncPlaybackRate=1),this.sizeCapManaged=f.capLevelToPlayerSize!==!0,this.fpsCapManaged=!(s&&`capLevelOnFPSDrop`in s),this.loadStarted=f.autoStartLoad!==!1;let p=new c.default(f);if(this.hls=p,this.armHoldBack(p,f),p.on(c.default.Events.FRAG_PARSED,(e,t)=>this.reanchorPartTimeline(p,t)),p.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,u&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&this.dropLevelsWidevineCannotPlay(p),this.measureLadder(p),this.applySizeCap(),this.loadSuspended=!1,e.paused&&this.schedulePauseSuspend(),l({type:`ready`})}),p.on(c.default.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},Yt)))}),p.on(c.default.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),p.on(c.default.Events.FRAG_LOADED,(e,t)=>{t?.frag?.type===`main`&&(this.mainFragsSinceTick+=1,this.bwFragsLoaded+=1,this.maybeRememberBandwidth(!1));let n=t?.frag?.stats,r=n?.loaded;typeof r==`number`&&(this.bytesLoaded+=r),!this.reportedFirstBytes&&typeof r==`number`&&r>0&&(this.reportedFirstBytes=!0,l({type:`firstBytes`}));let i=n?.loading;i&&i.end>0&&i.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(i.end-i.start))),this.requestTimesMs.length>En&&this.requestTimesMs.shift()),this.sampleHoldBack(t);let a=t?.frag?.url;if(a){let e=dt(a);e&&(this.cdnHost=e)}}),p.on(c.default.Events.LEVEL_LOADED,(e,t)=>{let n=t?.stats?.loaded;if(typeof n==`number`&&(this.playlistBytesLoaded+=n),this.reportedFirstPlaylist||(this.reportedFirstPlaylist=!0,l({type:`firstPlaylist`})),this.detectedLowLatency)return;let r=t.details;(r?.partList?.length||(r?.partTarget??0)>0)&&(this.detectedLowLatency=!0,l({type:`lowLatencyDetected`,value:!0}))}),p.on(c.default.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.prefetch){let e=this.prefetch;p.on(c.default.Events.KEY_LOADING,(t,n)=>{let r=n?.frag,i=zt(r?.type);if(r&&e.isActive(i))for(let t of Bt(p,r))e.prefetch(t.url,i,t.kind)}),p.on(c.default.Events.KEY_LOADED,(t,n)=>e.keyUsable(zt(n?.frag?.type)))}p.on(c.default.Events.KEY_LOADED,()=>{u&&!this.reportedDrmReady&&(this.reportedDrmReady=!0,l({type:`drmReady`}))}),this.endWatchdog&&clearInterval(this.endWatchdog),this.endWatchdog=setInterval(()=>{this.checkEndStale(),this.checkStarvation(),this.updateCatchUpBand(),this.checkFutileChase(),this.adaptHoldBack(),this.checkFrameDrops()},Zt),p.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>{this.renditionSwitches+=1;let n=this.lastLevelIndex>=0?p.levels[this.lastLevelIndex]:void 0,r=p.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(),l({type:`qualitychange`,index:t.level})}),p.on(c.default.Events.AUDIO_TRACK_SWITCHED,(e,t)=>l({type:`audiotrackchange`,id:t.id})),p.on(c.default.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>l({type:`texttrackchange`,id:t.id})),p.on(c.default.Events.ERROR,(e,t)=>this.onError(t)),p.loadSource(t.manifestUrl),p.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(t){if(e==null)this.bitrateCapLevel=-1;else{let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),this.bitrateCapLevel=n}this.pushCap()}}computeSizeCapTarget(){let e=this.hls;if(!e||e.levels.length===0)return null;let{video:t}=this.deps,n=t.getBoundingClientRect(),r=n.width,i=n.height;if(!r&&!i&&(r=t.width||0,i=t.height||0),!(r>0)||!(i>0))return null;let a=e.config??{},o=typeof self<`u`&&self.devicePixelRatio>0?self.devicePixelRatio:1,s=a.ignoreDevicePixelRatio?1:o;s=Math.min(s,a.maxDevicePixelRatio??1/0);let l=c.CapLevelController.getMaxLevelByMediaSize(e.levels,r*s,i*s),u=this.deps.sizeCapHeadroom;if(u==null&&o>=_n)return l;let d=u??gn,f=Number.isNaN(d)?gn:d===1/0?e.levels.length:Math.max(0,Math.floor(d));return vn(e.levels,l,f)}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?mn:hn;this.capTimer=setTimeout(()=>{this.capTimer=null,this.computeSizeCapTarget()===e?this.applySizeCap():this.onMediaResize()},t)}measureLadder(e){let t=e.levels.map(e=>e.height).filter(e=>!!e);this.ladderHeights=t.length?[...new Set(t)].sort((e,t)=>e-t):void 0,this.ladderTopBitrateKbps=e.levels.length?Math.round(Math.max(...e.levels.map(e=>e.bitrate))/1e3):0}dropLevelsWidevineCannotPlay(e){this.removeLevelsWhere(e,e=>Qe(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&z(e)!==`avc`&&!!z(e)));for(let n of t)Xe(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&&z(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:!z(e.videoCodec)||Qe(e.videoCodec)===!0))return console.warn(`havik-player: every rendition is ${a}, which Widevine may not play on this browser; keeping them`),!1;for(let t=r.length-1;t>=0;--t)e.removeLevel(r[t]);return console.info(`havik-player: skipped ${r.length} rendition(s) Widevine cannot play on this browser (${a})`),!0}applySizeCap(){if(!this.sizeCapManaged)return;this.capTimer&&=(clearTimeout(this.capTimer),null);let e=this.computeSizeCapTarget();e!=null&&(this.sizeCapLevel=e,this.pushCap())}pushCap(){let e=this.hls;if(!e)return;let t=[[`size`,this.sizeCapLevel??-1],[`bitrate`,this.bitrateCapLevel],[`fps`,this.fpsCapLevel(e)]],n=-1,r=null;for(let[e,i]of t)i>=0&&(n<0||i<n)&&(n=i,r=e);e.autoLevelCapping=n,this.pushedCapLevel=n,this.pushedCapReason=r}getAudioTracks(){return this.hls?this.hls.audioTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0,default:!!e.default})):[]}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}getTextTracks(){return this.hls?this.hls.subtitleTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0})):[]}setTextTrack(e){let t=this.hls;t&&(e<0?(t.subtitleTrack=-1,t.subtitleDisplay=!1):(t.subtitleTrack=e,t.subtitleDisplay=!0))}seekToLive(){let e=this.hls;e&&typeof e.liveSyncPosition==`number`&&(this.deps.video.currentTime=e.liveSyncPosition)}setLicenseUrls(e){e.widevine&&(this.licenseUrl=e.widevine)}getStats(){let e=this.hls,t=this.frameCounter.read(),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames,lowLatency:this.detectedLowLatency,bytesLoaded:this.bytesLoaded,playlistBytesLoaded:this.playlistBytesLoaded,renditionSwitches:this.renditionSwitches,liveRetargets:this.liveRetargets,holdBackSteps:this.holdBackSteps,fpsDownCaps:this.fpsDownCaps,licenseTimeMs:this.licenseTimeMs,upshifts:this.upshifts,downshifts:this.downshifts,requestCount:this.requestCount,requestErrors:this.requestErrors,requestTimesMs:[...this.requestTimesMs],ladderHeights:this.ladderHeights,ladderTopBitrateKbps:this.ladderTopBitrateKbps||void 0};if(this.cdnHost&&(n.cdnHost=this.cdnHost),this.licenseRequested&&(n.keySystem=`widevine`,n.drmSecurityLevel=`L3`),e){n.qualityPinned=!e.autoLevelEnabled,typeof e.latency==`number`&&(n.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(n.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(n.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let t=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;t&&(n.levelHeight=t.height);let r=e.autoLevelCapping,i=r>=0?e.levels[r]:void 0;if(i&&i.height>0){n.maxLevelHeight=i.height;let t=e.config??{};t.capLevelToPlayerSize!==!0&&t.capLevelOnFPSDrop!==!0&&r===this.pushedCapLevel&&this.pushedCapReason&&(n.capReason=this.pushedCapReason)}t?.videoCodec&&(n.videoCodec=t.videoCodec),t?.audioCodec&&(n.audioCodec=t.audioCodec),t&&typeof t.bitrate==`number`&&(n.renditionBitrateKbps=Math.round(t.bitrate/1e3)),typeof t?.details?.live==`boolean`&&(n.isLive=t.details.live,typeof e.liveSyncPosition==`number`&&(n.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return n}trackEnd(e){let t=e.details;if(t){if(t.live===!0){let e=!this.sawLive;this.sawLive=!0,e&&this.applyHoldBackPrior();let n=t.endSN??-1;n!==this.lastEndSN&&(this.lastEndSN=n,this.lastAdvanceMs=Date.now(),this.chaseSuspended&&this.resumeChasing());return}this.sawLive&&this.emitEnded(`endlist`)}}checkEndStale(){if(this.endedEmitted||!this.sawLive||this.lastAdvanceMs===0)return;if(typeof document<`u`&&document.hidden){this.lastAdvanceMs=Date.now();return}if(this.loadSuspended){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>$t&&this.suspendChasing(),e>Xt&&this.emitEnded(`stalled`)}resetStarvationWindow(){this.starvedTicks=0,this.deadTicks=0,this.mainFragsSinceTick=0,this.recentMainFrags=[]}clearKick(){this.kickPending=!1,this.kickTicks=0,this.kickKind=null}checkStarvation(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended)return;if(typeof document<`u`&&document.hidden||this.loadSuspended){this.resetStarvationWindow();return}let n=Date.now(),r=this.lastAdvanceMs!==0&&n-this.lastAdvanceMs<$t,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>sn,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=H(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>fn&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=un&&(this.clearKick(),this.starvationRebuilds<dn)){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>=cn,d=!i&&this.deadTicks>=fn&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=pn;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=ln))){this.starvationKicks+=1,this.kickPending=!0,this.kickTicks=0,this.kickKind=d?`dead`:`quiet`,this.clearRecoveryReset(),console.warn(d?`havik-player: video starved while hls.js keeps loading media it never plays (dead pipeline at the live edge) — restarting the load`:`havik-player: video starved while the live playlist advances (wedged hls.js fragment pipeline) — restarting the load`);try{e.stopLoad(),e.startLoad(-1)}catch(e){console.warn(`havik-player: starvation kick failed`,e)}}}updateCatchUpBand(){let e=this.hls;if(!e||this.catchUpRate<=1||this.chaseSuspended||this.loadSuspended)return;let t=e.latency,n=e.targetLatency;if(typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t))return;let r=t-n;!this.catchUpEngaged&&r>en?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=en&&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=Sn,this.fpsBadTicks=0)}resetFrameDropWindow(){this.fpsLastFrames=-1,this.fpsLastDropped=-1,this.fpsBadTicks=0}checkFrameDrops(){let e=this.hls,{video:t}=this.deps;if(!e||!this.fpsCapManaged||this.loadSuspended||t.paused||!e.autoLevelEnabled||typeof document<`u`&&document.hidden){this.resetFrameDropWindow();return}let{totalFrames:n,dropped:r}=H(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<bn||o<0){this.fpsBadTicks=0;return}if(this.fpsGraceTicks>0){--this.fpsGraceTicks,this.fpsBadTicks=0;return}if(o<=yn*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<xn)return;this.fpsBadTicks=0;let s=e.levels,c=s[e.currentLevel];if(!c)return;let l=s.filter(e=>e.height>0&&e.height<c.height),u=(l.length?l:s.filter(e=>e.bitrate<c.bitrate)).map(e=>e.bitrate).sort((e,t)=>t-e)[0];u!=null&&(this.fpsCapBitrate!=null&&u>=this.fpsCapBitrate||(this.fpsCapBitrate=u,l.length&&(this.fpsCapFailedHeight=c.height),this.fpsDownCaps+=1,console.warn(`havik-player: dropping ${Math.round(100*o/a)}% of frames at ${c.height}p — capping quality below it`),this.pushCap()))}resetChaseWindow(){this.chaseLatency=-1,this.chaseTicks=0}checkFutileChase(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||typeof document<`u`&&document.hidden){this.resetChaseWindow();return}let n=e.latency,r=t.playbackRate,i=e.config.maxLiveSyncPlaybackRate;if(!(!t.paused&&typeof i==`number`&&i>1&&r>=Math.min(rn,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=nn){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<tn)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+an||(console.warn(`havik-player: catch-up at ${r}x not gaining on the live edge (latency ${n.toFixed(1)}s); holding at ${s.toFixed(1)}s`),this.liveRetargets+=1,e.targetLatency=s,this.deps.emit({type:`livetargetchange`,change:{targetSeconds:s,previousSeconds:o,reason:`futile-chase`}}))}armHoldBack(e,t){this.holdBackEnabled&&(this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[],this.holdBackBase<0&&typeof t.liveSyncDuration==`number`&&(this.holdBackBase=t.liveSyncDuration),this.holdBackApplied>0&&(e.targetLatency=this.holdBackApplied))}applyHoldBackPrior(){let e=this.hls;if(!this.holdBackEnabled||this.holdBackPriorChecked||!e||(this.holdBackPriorChecked=!0,this.holdBackApplied>0||this.holdBackStepCount>0))return;let t=e.targetLatency;if(this.holdBackBase<0&&typeof t==`number`&&t>0&&(this.holdBackBase=t),this.holdBackBase<0)return;let n=In();if(!(n>=Fn))return;let r=typeof t==`number`&&t>0?t:this.holdBackBase,i=Math.min(this.holdBackCeiling(e),this.holdBackBase+X);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:Pn,r=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;return r>1?Math.min(n,r-1):n}sampleHoldBack(e){if(!this.holdBackEnabled||typeof document<`u`&&document.hidden)return;let t=e.frag?.type;if(t!==`main`&&t!==`audio`)return;let n=e.part?e.part.duration:this.detectedLowLatency?0:e.frag?.duration;if(typeof n!=`number`||!(n>0))return;let r=(e.part??e.frag)?.stats?.loading;if(!r||!(r.start>0)||!(r.end>0))return;let i=r.first>r.start?r.first:r.end,a=Math.max(0,i-r.start)/(n*1e3);this.holdBackSamples.push({t:Date.now(),ratio:a}),this.holdBackSamples.length>256&&this.holdBackSamples.shift()}adaptHoldBack(){if(!this.holdBackEnabled)return;let e=this.hls;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||typeof document<`u`&&document.hidden){this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[];return}let t=Date.now(),n=t-Dn,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<On){this.holdBackSlowTicks=0;return}let c=r.map(e=>e.ratio).sort((e,t)=>e-t),l=Y(c,95),u=Y(c,50),d=Math.round(l*1e3);if(l>=kn&&u>=An){if(this.holdBackFastSince=0,this.holdBackSlowTicks+=1,this.holdBackSlowTicks<Mn)return;this.holdBackSlowTicks=0;let t=Math.ceil((s-o)/X),n=Math.ceil((a-o)/X-1e-9);if(n>this.holdBackStepCount&&(this.holdBackStepCount=n),this.holdBackStepCount>=t)return;this.holdBackStepCount+=1;let r=Math.min(s,o+this.holdBackStepCount*X);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>=jn){this.holdBackFastSince=0;return}if(this.holdBackFastSince===0){this.holdBackFastSince=t;return}if(t-this.holdBackFastSince<Nn||(this.holdBackFastSince=t,this.holdBackStepCount===0||a!==this.holdBackApplied))return;--this.holdBackStepCount;let f=Math.max(o,o+this.holdBackStepCount*X);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?Ht:Be()??Ht}maybeRememberBandwidth(e){if(this.deps.rememberBandwidth===!1||this.bwFragsLoaded<Ut)return;let t=Date.now();if(!e&&t-this.bwSavedAt<Wt)return;let n=this.hls?.bandwidthEstimate;typeof n!=`number`||!Number.isFinite(n)||n<=0||(this.bwSavedAt=t,Ve(n))}destroy(){if(this.maybeRememberBandwidth(!0),this.detachFrames?.(),this.detachFrames=null,this.prefetch?.destroy(),this.prefetch=null,this.clearRecoveryReset(),this.capTimer&&=(clearTimeout(this.capTimer),null),this.capObserver&&=(this.capObserver.disconnect(),null),this.unwatchDprChanges(),this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onSeeking&&=(this.deps.video.removeEventListener(`seeking`,this.onSeeking),null),this.onTimeUpdate&&=(this.deps.video.removeEventListener(`timeupdate`,this.onTimeUpdate),null),this.onPause&&=(this.deps.video.removeEventListener(`pause`,this.onPause),null),this.onPlay&&=(this.deps.video.removeEventListener(`play`,this.onPlay),null),this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),this.licenseRetryTimer&&=(clearTimeout(this.licenseRetryTimer),null),this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during teardown`,e)}this.hls=null}}clearRecoveryReset(){this.recoveryResetTimer&&=(clearTimeout(this.recoveryResetTimer),null)}scheduleLicenseRetry(e){if(e.details!==c.default.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED&&e.details!==c.default.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>=qt)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{this.licenseRetryTimer=null,this.rebuildInstance(`license retry`)},n),!0}rebuildInstance(e){if(this.hls){try{this.hls.destroy()}catch(t){console.warn(`havik-player: hls.js destroy() threw during ${e}`,t)}this.hls=null,this.startHls(),this.armFrameDropGrace()}}onError(e){if(e.type===c.default.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===c.default.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===c.default.ErrorTypes.NETWORK_ERROR){if(this.networkRecoveries<Kt){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===c.default.ErrorTypes.MEDIA_ERROR){if(this.mediaRecoveries<Gt){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??``,a=t===`DRM`&&n===403&&e.details===c.default.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED?d(jt(e.networkDetails)):void 0;return new l(t===`DRM`?f(n,a):n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`,a?{serverCode:a}:void 0)}},Bn=15e3,Vn=6e5,Hn=3e5,Un=100,Z=1,Wn=1e3,Gn=3e4,Kn=1e3,qn={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},Jn={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`},Yn=new Set([`INVALID_URN`,`NOT_FOUND`,`GEO_DENIED`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),Q={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 Xn(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 Zn=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),Qn=new Set,$n=new Set,er=new Set,tr=e=>`this page's Content-Security-Policy blocks QoE beacons. Add ${e} to connect-src; until then none are sent.`;function nr(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(Qn.has(t)&&!$n.has(t)){$n.add(t),b(tr(new URL(t).origin));for(let e of er)e.noteCspBlocked()}}function rr(e,t){return b(t,e),{disabledReason:t}}function ir(e,t,n){if(n)return t&&!Zn(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return rr(`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=Xn(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return rr(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 ar=class{opts;url;cspKey;now;seq=0;pending=[];timer=null;endedFlag=!1;lastBytes=0;lastPlaylistBytes=0;lastDropped=0;lastSwitches=0;playingSinceMs=null;hiddenSinceMs=null;playingTotalMs=0;hiddenTotalMs=0;lastHbPlayingMs=0;lastHbHiddenMs=0;lastHbRebufferMs=0;lastHbRebufferCount=0;lastHbActiveMs=0;rebufferCount=0;rebufferTotalMs=0;bufferingSinceMs=null;isBuffering=!1;errorCount=0;seekCount=0;pauseCount=0;isPlaying=!1;isHidden=!1;isMuted=!1;activeSinceMs=null;activeTotalMs=0;mutedSinceMs=null;mutedTotalMs=0;lastHbMutedMs=0;volumeChanges=0;muteChanges=0;presentation=`inline`;presentationSinceMs;fullscreenTotalMs=0;pipTotalMs=0;waitingSinceMs=null;waitingTotalMs=0;firstAudioMs=0;timeToFirstStallMs=0;lastStallMs=0;lastErrorMs=0;lastSeekMs=-1;stallIsSeekInduced=!1;lastErrorStage=null;sawFirstBytes=!1;mediaInfoSignature=``;lastUpshifts=0;lastDownshifts=0;lastDecoded=0;lastRequestCount=0;lastRequestErrors=0;pendingStart=null;firstFlushTimer=null;idleTimer=null;lastTickMs=0;bornMs;startupAnchorMs;startupTimeMs=0;manifestLoadMs=0;firstFragLoadMs=0;firstPlaylistMs=0;drmSetupMs=0;onPagehide=()=>this.end(`END_REASON_PAGEHIDE`);cspBlockedNoted=!1;onFreeze=()=>{this.endedFlag||this.flush(!0)};onResume=()=>this.checkSuspension(this.now());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())};constructor(e){this.opts={...e,heartbeatMs:e.heartbeatMs??Bn,idleMs:e.idleMs??Vn},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(),Wn),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&&Qn.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,nr),er.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,Hn);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(Z,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(Z,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(Z,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:Q[e]??`PLAYER_STATE_UNSPECIFIED`,toState:Q[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:qn[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<Kn}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(Z,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=Z),this.firstPlaylistMs>0&&(this.firstPlaylistMs=Z),this.firstFragLoadMs>0&&(this.firstFragLoadMs=Z),this.drmSetupMs>0&&(this.drmSetupMs=Z))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(Z,this.now()-this.startupAnchorMs))}noteFirstPlaylist(){this.firstPlaylistMs===0&&(this.firstPlaylistMs=Math.max(Z,this.now()-this.startupAnchorMs))}noteDrmReady(){this.drmSetupMs===0&&(this.drmSetupMs=Math.max(Z,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(Z,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(Yn.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=Q[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=Y(n,50),o.requestTimeP95Ms=Y(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=Jn[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,er.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<=Gn&&(i.abandonAfterStallMs=Math.max(Z,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=Gn&&(i.abandonAfterErrorMs=Math.max(Z,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?.(tr(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&$n.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>Un;){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 or(){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 sr(){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 cr(){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 lr(e){let t=or(),n={deviceClass:sr(),integration:t.integration,...cr()};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 ur(){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 dr=`2.23.1`,fr={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`},pr={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 mr(e,t){let n={...fr,...t};for(let t of Object.keys(pr))e.style.setProperty(pr[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var hr=`havik-player-styles`,gr=`
|
|
3
|
+
`));t&&typeof t.state==`string`&&e.onState(t)}catch{}},l=/\r\n\r\n|\n\n|\r\r/,u=async(e,t,n)=>{let r=e.getReader(),a=new TextDecoder,s=``,u=!1,d,f=()=>{i&&(clearTimeout(d),d=setTimeout(()=>{n(),r.cancel().catch(()=>{})},i))};try{for(f();;){let{value:e,done:n}=await r.read();if(n)return;e&&e.length>0&&(f(),u||(u=!0,t())),s+=a.decode(e,{stream:!0});let i;for(;(i=l.exec(s))!==null;)c(s.slice(0,i.index)),s=s.slice(i.index+i[0].length);if(o)return}}finally{clearTimeout(d),await r.cancel().catch(()=>{})}};return(async()=>{let r=t;for(;!o;){let c=new AbortController,l=()=>c.abort();a.signal.addEventListener(`abort`,l,{once:!0});let d=null,f,p=()=>{d=`no data for ${i}ms`,c.abort()};try{let n=await h(e.credential);if(o)return;let a=v(e.eventsBaseUrl,`/v1/events/${encodeURIComponent(e.matchUrn)}`);i&&(f=setTimeout(()=>{d=`no response headers within ${i}ms`,c.abort()},i));let s=await fetch(a,{method:`GET`,headers:{"x-api-key":n.apiKey,accept:`text/event-stream`},signal:c.signal,cache:`no-store`,credentials:`omit`,mode:`cors`});if(clearTimeout(f),o)return;!s.ok||!s.body?e.onError?.(Error(`live-state subscribe failed: HTTP ${s.status}`)):await u(s.body,()=>{r=t},p)}catch(t){if(o||a.signal.aborted)return;d||e.onError?.(t)}finally{clearTimeout(f),a.signal.removeEventListener(`abort`,l),c.abort()}if(o)return;d&&e.onError?.(Error(`live-state subscribe idle: ${d} — reconnecting`)),await s(r),r=Math.min(n,r*2)}})(),{close(){o||(o=!0,a.abort())}}}function A(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var j=`havik.player.deviceId`,M;function N(){if(M)return M;try{let e=globalThis.localStorage?.getItem(j);if(e)return M=e,e}catch{}let e=je();M=e;try{globalThis.localStorage?.setItem(j,e)}catch{}return e}function Ae(){M=void 0;try{globalThis.localStorage?.removeItem(j)}catch{}}function je(){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 Me(e,t,n={}){let r={"x-api-key":t.apiKey,"X-Match-Urn":e.matchUrn,"X-Device-Id":n.deviceId??N(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var P=`havik.player.bandwidth`,Ne=.8,Pe=2e7,Fe=3e5;function Ie(){return globalThis.navigator?.connection}function Le(){let e=Ie()?.type;return typeof e==`string`&&e!==``&&e!==`unknown`?e:`any`}function Re(){let e=Ie()?.downlink;return typeof e==`number`&&Number.isFinite(e)&&e>0?e*1e6:void 0}function ze(){try{let e=globalThis.localStorage?.getItem(P);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function Be(e=Date.now()){let t=ze()[Le()];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=Re(),i=r===void 0?t.bps:Math.min(t.bps,r);return Math.round(Math.min(Pe,Math.max(Fe,i*Ne)))}function Ve(e,t=Date.now()){if(!Number.isFinite(e)||e<=0)return;let n=ze();n[Le()]={bps:Math.round(e),at:t};try{globalThis.localStorage?.setItem(P,JSON.stringify(n))}catch{}}function He(){try{globalThis.localStorage?.removeItem(P)}catch{}}var Ue=new WeakMap;function We(e,t){let n=Ue.get(e);n||(n=new Map,Ue.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 F(){return typeof navigator<`u`&&typeof navigator.requestMediaKeySystemAccess==`function`}var I=[`SW_SECURE_DECODE`,`SW_SECURE_CRYPTO`];function Ge(e){return e.startsWith(`com.widevine`)}function L(e,t){if(!Ge(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=I.indexOf(e.robustness);return n===-1||I.indexOf(t)>n})},r=I.flatMap(e=>t.filter(t=>n(t,e)).map(t=>({...t,videoCapabilities:t.videoCapabilities?.map(t=>({...t,robustness:e}))})));return[...t,...r]}function Ke(e){return(t,n)=>F()?navigator.requestMediaKeySystemAccess(t,L(t,n)).then(t=>({keySystem:t.keySystem,getConfiguration:()=>t.getConfiguration(),createMediaKeys:()=>We(e,t)})):Promise.reject(Error(`navigator.requestMediaKeySystemAccess is unavailable — EME needs a secure context (https, or localhost)`))}var R={video:`SW_SECURE_DECODE`,audio:`SW_SECURE_CRYPTO`,scheme:`cbcs`};function qe(e){if(!F())return;let t=(e,t)=>({contentType:e,robustness:t,encryptionScheme:R.scheme});Ke(e)(`com.widevine.alpha`,[{initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],audioCapabilities:[t(`audio/mp4; codecs="mp4a.40.2"`,R.audio)],videoCapabilities:[t(`video/mp4; codecs="avc1.42e01e"`,R.video)]}]).then(e=>e.createMediaKeys()).catch(()=>{})}function z(e){let t=B(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 B(e){return(e??``).trim().toLowerCase()}var Je={hevc:`hvc1.1.6.L93.90`,dv:`dvh1.05.06`,av1:`av01.0.05M.08`,vp9:`vp09.00.10.08`},Ye=new Map,V=new Map;function Xe(e){let t=B(e),n=Ye.get(t);if(n)return n;let r={initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],videoCapabilities:[{contentType:`video/mp4; codecs="${e.trim()}"`,robustness:R.video,encryptionScheme:R.scheme}]},i=(async()=>{try{return await navigator.requestMediaKeySystemAccess(`com.widevine.alpha`,L(`com.widevine.alpha`,[r])),!0}catch{return!1}})().then(e=>(V.set(t,e),e));return Ye.set(t,i),i}function Ze(){if(F())for(let e of Object.values(Je))Xe(e)}function Qe(e){let t=z(e);if(t)return t===`avc`?!0:V.get(B(e))??V.get(B(Je[t]))}var $e=5e3,et=`video/mp4; codecs="avc1.42E01E"`,tt=`audio/mp4; codecs="mp4a.40.2"`,nt={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function rt(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:et,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:tt,robustness:``,encryptionScheme:`cbcs`}]}]:L(`com.widevine.alpha`,[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:et,robustness:R.video,encryptionScheme:R.scheme}],audioCapabilities:[{contentType:tt,robustness:R.audio,encryptionScheme:R.scheme}]}])}function it(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 at(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??$e,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=nt[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 it((await it(i(n,rt(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 ot=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function st(e){return ot.test(e)}var ct={integration:`https://feed-dev.oddin-video.gg`,production:`https://feed.oddin-video.gg`};function lt(e){let t=Object.prototype.hasOwnProperty.call(ct,e)?ct[e]:void 0;if(!t)throw new l(`INTERNAL`,0,`unknown env ${JSON.stringify(e)} — expected 'integration' or 'production'`);return t}var ut={droppedFrames:0};function dt(e){try{return new URL(e).host}catch{return``}}var ft=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function pt(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`||ft.test(i.name))&&i.startTime>=n){let e=dt(i.name);e&&(t=e,n=i.startTime)}return t}function H(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var mt=class{video;baseFrames=0;baseDropped=0;lastFrames=0;lastDropped=0;constructor(e){this.video=e}read(){let e=H(this.video);return e.totalFrames<this.lastFrames&&(this.baseFrames+=this.lastFrames),e.dropped<this.lastDropped&&(this.baseDropped+=this.lastDropped),this.lastFrames=e.totalFrames,this.lastDropped=e.dropped,{dropped:this.baseDropped+e.dropped,totalFrames:this.baseFrames+e.totalFrames}}attach(){let e=()=>void this.read();return this.video.addEventListener(`timeupdate`,e),this.video.addEventListener(`seeking`,e),()=>{this.video.removeEventListener(`timeupdate`,e),this.video.removeEventListener(`seeking`,e)}}};function ht(e,t){let n=[[`playing`,()=>t(`playing`)],[`waiting`,()=>t(`buffering`)],[`stalled`,()=>t(`buffering`)],[`pause`,()=>{e.ended||t(`paused`)}],[`ended`,()=>t(`ended`)]];for(let[t,r]of n)e.addEventListener(t,r);return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}var gt=2e3,_t=3,U=500,vt=6e3,yt=.25,bt=250,xt=.05,St=4,Ct=12e3,wt=.25,Tt=1e3;function Et(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 W(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function G(){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 Dt(){if(typeof navigator>`u`||!G())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var K=class{name=`native`;deps;onLoaded;onError;onEncrypted;fairplayLicenseUrl;keySession=null;fairplayArmed=!1;onVisibility=null;onPageShow=null;hiddenSince=null;refocusTimer=null;edgeTimer=null;onEdgeReset=null;lastBufferedEnd=null;bufferedAdvancedAt=null;lastSeekableEnd=null;edgeStampedAt=null;lastTickAt=null;endedEmitted=!1;fairplayKeyIV;loadStarted;preloadTouched=!1;savedPreload=null;cdnHost=``;builtAt;frameCounter;detachFrames=null;constructor(e){this.deps=e,this.frameCounter=new mt(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 l(`DRM_CLIENT`,0,`native HLS engine cannot satisfy this DRM (Widevine requires the hls.js engine); use engine "auto"/"hls" on a Widevine-capable browser`),fatal:!0});return}this.armFairPlay()}let r=!this.loadStarted;this.onLoaded=r?void 0:()=>n({type:`ready`}),this.onError=()=>n({type:`error`,error:new l(`INTERNAL`,0,`native HLS playback error`),fatal:!0}),this.onLoaded&&e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=kt(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:a}=this.deps,o=t.drm?.fairplay;if(!o)return;this.fairplayLicenseUrl=o.licenseUrl;let s=(e,t,n,r)=>a({type:`error`,error:new l(f(t,r),t,e,r?{serverCode:r}:void 0),fatal:n}),c=async e=>{try{return await e.text()}catch{return``}};this.onEncrypted=a=>{let l=a;l.initData&&!this.fairplayArmed&&(this.fairplayArmed=!0,this.fairplayKeyIV=Et(l.initData),(async()=>{try{let a=await(await navigator.requestMediaKeySystemAccess(`com.apple.fps`,[{initDataTypes:[l.initDataType],videoCapabilities:[{contentType:`application/vnd.apple.mpegurl`,robustness:``}],distinctiveIdentifier:`not-allowed`,persistentState:`not-allowed`,sessionTypes:[`temporary`]}])).createMediaKeys(),u=await fetch(o.certificateUrl,{headers:{"x-api-key":n.apiKey}});if(!u.ok){this.fairplayArmed=!1,s(`FairPlay certificate request failed: ${u.status}`,u.status,!0);return}await a.setServerCertificate(await u.arrayBuffer()),await e.setMediaKeys(a);let f=a.createSession();this.keySession=f,f.addEventListener(`message`,e=>{(async()=>{try{let a=await fetch(this.fairplayLicenseUrl??o.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?d(await c(a)):void 0;s(`FairPlay license request failed: ${a.status}`,a.status,!0,e);return}await f.update(new Uint8Array(await a.arrayBuffer()))}catch(e){s(`FairPlay license request failed: ${String(e)}`,0,!0)}})()}),await f.generateRequest(l.initDataType,l.initData)}catch(e){this.fairplayArmed=!1,s(`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||=pt(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<=St,!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=q();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=gt&&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=q,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=U;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+yt),s=Math.max(r,t()-n)>=vt;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,U)};this.refocusTimer=setTimeout(i,U)}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=Ot(e,e.currentTime);t!=null&&((this.lastBufferedEnd==null||Math.abs(t-this.lastBufferedEnd)>=xt)&&(this.bufferedAdvancedAt=q()),this.lastBufferedEnd=t)},bt)}checkEndStale(){if(this.endedEmitted)return;let e=q(),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)>=wt;this.lastSeekableEnd=n;let i=this.deps.video,a=typeof document<`u`&&document.visibilityState===`hidden`;if(r||t>Tt||a||i.paused){this.edgeStampedAt=e;return}e-(this.edgeStampedAt??e)>Ct&&(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=Ot(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,(q()-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-_t,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 q(){return typeof performance<`u`?performance.now():Date.now()}function Ot(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 kt(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function J(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 At=4096;function jt(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>At))try{return new TextDecoder().decode(n)}catch{return}}var Mt=15e3,Nt=5e3,Pt=6;function Ft(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var It=class{cmcd;entries=new Map;keyed=new Set;perTrack=new Map;stats={started:0,served:0,missed:0,failed:0,expired:0};constructor(e={}){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=Ft(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;if(i>=Pt)return;this.perTrack.set(t,i+1);let a=new AbortController,o={started:performance.now(),first:0,bytes:Promise.resolve(null),abort:a};o.bytes=fetch(this.withCmcd(e,t,n),{credentials:`omit`,mode:`cors`,signal:a.signal}).then(async e=>(o.first=performance.now(),e.ok?e.arrayBuffer():null)).catch(()=>null),this.entries.set(r,o),this.stats.started+=1,setTimeout(()=>{this.entries.get(r)===o&&(this.entries.delete(r),a.abort(),this.stats.expired+=1)},Mt)}take(e){let t=Ft(e),n=this.entries.get(t);return n&&this.entries.delete(t),n}destroy(){for(let e of this.entries.values())e.abort.abort();this.entries.clear()}withCmcd(e,t,n){let{sessionId:r,contentId:i}=this.cmcd;if(!r&&!i)return e;let a=[];i&&a.push(`cid="${i}"`),a.push(`ot=${n===`init`?`i`:t===`audio`?`a`:`v`}`),a.push(`sf=h`),r&&a.push(`sid="${r}"`),a.push(`st=ll`);try{let t=new URL(e);return t.searchParams.set(`CMCD`,a.join(`,`)),t.toString()}catch{return e}}};function Lt(e){let t=c.default.DefaultConfig?.loader;if(typeof t!=`function`)return;class n extends t{served=!1;cancelled=!1;stats=Rt();load(t,n,r){let i=t.rangeEnd?void 0:e.take(t.url);if(!i){super.load(t,n,r);return}this.served=!0;let a=performance.now(),o=n?.loadPolicy?.maxTimeToFirstByteMs||Nt,s=setTimeout(()=>{!this.cancelled&&this.served&&(i.abort.abort(),e.stats.failed+=1,this.served=!1,super.load(t,n,r))},o);i.bytes.then(o=>{if(clearTimeout(s),this.cancelled||!this.served)return;if(!o){e.stats.failed+=1,this.served=!1,super.load(t,n,r);return}e.stats.served+=1;let c=this.stats;c.loading.start=a,c.loading.first=Math.max(a,i.first||a),c.loading.end=performance.now(),c.loaded=c.total=o.byteLength,r.onSuccess({url:t.url,data:o},c,t,null)})}abort(){if(this.served){this.cancelled=!0,this.stats.aborted=!0;return}super.abort()}}return n}function Rt(){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 zt(e){return e===`audio`?`audio`:`main`}function Bt(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 Y(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}function Vt(){return c.default.isSupported()}var Ht=1e6,Ut=20,Wt=1e4,Gt=3,Kt=5,qt=3,Jt=1e4,Yt=3e4,Xt=12e3,Zt=3e3,Qt=.02,$t=6e3,en=.5,tn=3,nn=.5,rn=1.1,an=.25,on=5e3,sn=4e3,cn=2,ln=5,un=2,dn=2,fn=4,pn=4,mn=2e3,hn=3e4,gn=1,_n=2;function vn(e,t,n){if(n<=0||t<0||t>=e.length)return t;let r=(t,n)=>e[t].width===e[n].width&&e[t].height===e[n].height,i=t=>{for(;t+1<e.length&&r(t+1,t);)t++;return t},a=i(t);for(let t=0;t<n&&a+1<e.length;t++)a=i(a+1);return a}var yn=.2,bn=30,xn=2,Sn=2,Cn=2,wn=9,Tn=.5,En=64,Dn=1e4,On=8,kn=.6,An=.4,jn=.4,Mn=2,Nn=6e4,X=.5,Pn=3.5,Fn=300;function In(){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 Ln(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Cn;let t=Math.max(12,e.liveSyncDuration+wn);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),Rn(e,e.liveSyncDuration)}function Rn(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 zn=class{name=`hls`;hls=null;deps;licenseUrl;detectedLowLatency=!1;bytesLoaded=0;prefetch=null;reportedFirstPlaylist=!1;reportedFirstBytes=!1;reportedDrmReady=!1;playlistBytesLoaded=0;renditionSwitches=0;licenseTimeMs=0;licenseRequested=!1;upshifts=0;downshifts=0;lastLevelIndex=-1;requestCount=0;requestErrors=0;requestTimesMs=[];cdnHost=``;ladderHeights;ladderTopBitrateKbps=0;mediaRecoveries=0;networkRecoveries=0;licenseRecoveries=0;recoveryResetTimer=null;networkRetryTimer=null;licenseRetryTimer=null;onVisibility=null;onSeeking=null;onPause=null;onPlay=null;pauseSuspendTimer=null;loadSuspended=!1;stopped=!1;sawLive=!1;lastEndSN=-1;lastAdvanceMs=0;endWatchdog=null;endedEmitted=!1;lastFragLoadingMs=0;starvedTicks=0;starvationKicks=0;kickPending=!1;kickTicks=0;starvationRebuilds=0;kickKind=null;starvedFrames=0;deadTicks=0;mainFragsSinceTick=0;bwFragsLoaded=0;bwSavedAt=0;recentMainFrags=[];chaseSuspended=!1;savedLiveMaxLatency;savedMaxSyncRate;chaseLatency=-1;catchUpRate=1;catchUpEngaged=!1;onTimeUpdate=null;chaseTicks=0;liveRetargets=0;holdBackEnabled;holdBackSamples=[];holdBackBase=-1;holdBackStepCount=0;holdBackApplied=0;holdBackSlowTicks=0;holdBackFastSince=0;holdBackSteps=0;holdBackPriorChecked=!1;capObserver=null;capTimer=null;sizeCapLevel=null;bitrateCapLevel=-1;pushedCapLevel=-1;pushedCapReason=null;fpsCapBitrate=null;fpsCapFailedHeight=null;fpsCapManaged=!0;fpsLastFrames=-1;fpsLastDropped=-1;fpsBadTicks=0;fpsGraceTicks=0;fpsDownCaps=0;sizeCapManaged=!0;dprMedia=null;onDprChange=null;loadStarted;frameCounter;detachFrames=null;constructor(e){this.deps=e,this.holdBackEnabled=e.adaptiveHoldBack!==!1,this.frameCounter=new mt(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=W(n)&&G(),a=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!a){r({type:`error`,error:new l(`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&&a&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&(qe(n),Ze()),this.startHls(),t!==!1&&typeof document<`u`&&(this.onVisibility=()=>{let e=this.hls;if(document.visibilityState!==`visible`||!e)return;let t=e.liveSyncPosition;if(typeof t!=`number`)return;let r=typeof e.targetLatency==`number`&&e.targetLatency>0?e.targetLatency:3;t-n.currentTime>Math.max(r*3,8)&&(n.currentTime=t)},document.addEventListener(`visibilitychange`,this.onVisibility)),this.onSeeking=()=>{this.clampOverSeek(),this.loadSuspended&&(this.resumeLoading(),this.schedulePauseSuspend())},n.addEventListener(`seeking`,this.onSeeking),this.onTimeUpdate=()=>this.updateCatchUpBand(),n.addEventListener(`timeupdate`,this.onTimeUpdate),this.onPause=()=>this.schedulePauseSuspend(),this.onPlay=()=>this.resumeLoading(),n.addEventListener(`pause`,this.onPause),n.addEventListener(`play`,this.onPlay),this.sizeCapManaged&&typeof ResizeObserver<`u`&&(this.capObserver=new ResizeObserver(()=>this.onMediaResize()),this.capObserver.observe(n),this.watchDprChanges())}schedulePauseSuspend(){this.pauseSuspendTimer||this.loadSuspended||this.stopped||!this.loadStarted||(this.pauseSuspendTimer=setTimeout(()=>{this.pauseSuspendTimer=null;let{video:e}=this.deps;if(e.paused&&!e.ended&&!this.stopped&&this.hls){try{this.hls.stopLoad()}catch{return}this.loadSuspended=!0}},on))}resumeLoading(){if(this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.resetChaseWindow(),this.resetFrameDropWindow(),this.loadSuspended&&(this.loadSuspended=!1,!this.stopped&&this.hls)){this.lastAdvanceMs=Date.now(),this.lastFragLoadingMs=0,this.resetStarvationWindow(),this.resetChaseWindow(),this.clearKick();try{this.hls.startLoad(-1)}catch{}}}startLoad(){this.loadStarted||(this.loadStarted=!0,this.deps.video.paused&&this.schedulePauseSuspend(),this.hls?.startLoad(-1))}watchDprChanges(){if(typeof matchMedia!=`function`)return;this.unwatchDprChanges();let e=typeof self<`u`&&self.devicePixelRatio||1,t=matchMedia(`(resolution: ${e}dppx)`);if(typeof t.addEventListener!=`function`)return;let n=()=>{this.onMediaResize(),this.watchDprChanges()};t.addEventListener(`change`,n),this.dprMedia=t,this.onDprChange=n}unwatchDprChanges(){this.dprMedia&&this.onDprChange&&this.dprMedia.removeEventListener(`change`,this.onDprChange),this.dprMedia=null,this.onDprChange=null}clampOverSeek(){let e=this.hls;if(!e||this.chaseSuspended||(e.levels[e.currentLevel]??e.levels[e.loadLevel])?.details?.live!==!0)return;let t=e.liveSyncPosition;if(typeof t!=`number`||!Number.isFinite(t))return;let{video:n}=this.deps;n.currentTime<=t+Tn||(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)<Qt)){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:l}=this.deps;this.clearKick(),this.resetStarvationWindow(),this.resetChaseWindow(),this.resetFrameDropWindow(),this.lastFragLoadingMs=0,this.lastEndSN=-1,this.lastAdvanceMs=0;let u=t.drmEnabled&&!!(t.drm?.widevine?.licenseUrl||t.drm?.fairplay?.licenseUrl),d=W(this.deps.video)&&G(),f={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,liveDurationInfinity:!0,maxBufferHole:.5,maxLiveSyncPlaybackRate:d?1:1.1,abrEwmaDefaultEstimate:this.startEstimate(),capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...u?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:R.video,audioRobustness:R.audio,videoEncryptionScheme:R.scheme,audioEncryptionScheme:R.scheme},...F()?{requestMediaKeySystemAccessFunc:Ke(e)}:{},licenseXhrSetup:(e,a)=>{let o=performance.now(),s=()=>{e.open(`POST`,this.licenseUrl??a,!0),e.setRequestHeader(`x-api-key`,n.apiKey),e.setRequestHeader(`X-Match-Urn`,t.matchUrn),e.setRequestHeader(`X-Device-Id`,r),i&&e.setRequestHeader(`X-User-Id`,i),this.licenseRequested=!0,e.addEventListener(`loadend`,()=>{this.licenseTimeMs===0&&(this.licenseTimeMs=Math.max(1,Math.round(performance.now()-o)))})},{freshLicenseUrl:c}=this.deps;if(!c||!J(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),Jt)});return Promise.race([c().catch(()=>void 0),d]).finally(()=>clearTimeout(u)).then(e=>{if(!this.hls||this.hls!==l)throw Error(`havik-player: engine torn down during refresh`);e&&(this.licenseUrl=e),s()})}}:{},...t.analytics?.sid?{cmcd:{sessionId:t.analytics.sid,contentId:t.matchUrn,useHeaders:!1}}:{},...s};if(this.prefetch?.destroy(),this.prefetch=null,u&&this.deps.mediaDuringKey!==!1&&!f.fLoader){let e=new It({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=Lt(e);n&&(this.prefetch=e,f.fLoader=n)}Ln(f),this.catchUpRate=typeof f.maxLiveSyncPlaybackRate==`number`?f.maxLiveSyncPlaybackRate:1,this.catchUpEngaged=!1,this.catchUpRate>1&&(f.maxLiveSyncPlaybackRate=1),this.sizeCapManaged=f.capLevelToPlayerSize!==!0,this.fpsCapManaged=!(s&&`capLevelOnFPSDrop`in s),this.loadStarted=f.autoStartLoad!==!1;let p=new c.default(f);if(this.hls=p,this.armHoldBack(p,f),p.on(c.default.Events.FRAG_PARSED,(e,t)=>this.reanchorPartTimeline(p,t)),p.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,u&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&this.dropLevelsWidevineCannotPlay(p),this.measureLadder(p),this.applySizeCap(),this.loadSuspended=!1,e.paused&&this.schedulePauseSuspend(),l({type:`ready`})}),p.on(c.default.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},Yt)))}),p.on(c.default.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),p.on(c.default.Events.FRAG_LOADED,(e,t)=>{t?.frag?.type===`main`&&(this.mainFragsSinceTick+=1,this.bwFragsLoaded+=1,this.maybeRememberBandwidth(!1));let n=t?.frag,r=n?.stats?.loaded;typeof r==`number`&&(this.bytesLoaded+=r),!this.reportedFirstBytes&&typeof r==`number`&&r>0&&(this.reportedFirstBytes=!0,l({type:`firstBytes`}));let i=(t?.part??n)?.stats?.loading;i&&i.end>0&&i.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(i.end-i.start))),this.requestTimesMs.length>En&&this.requestTimesMs.shift()),this.sampleHoldBack(t);let a=n?.url;if(a){let e=dt(a);e&&(this.cdnHost=e)}}),p.on(c.default.Events.LEVEL_LOADED,(e,t)=>{let n=t?.stats?.loaded;if(typeof n==`number`&&(this.playlistBytesLoaded+=n),this.reportedFirstPlaylist||(this.reportedFirstPlaylist=!0,l({type:`firstPlaylist`})),this.detectedLowLatency)return;let r=t.details;(r?.partList?.length||(r?.partTarget??0)>0)&&(this.detectedLowLatency=!0,l({type:`lowLatencyDetected`,value:!0}))}),p.on(c.default.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.prefetch){let e=this.prefetch;p.on(c.default.Events.KEY_LOADING,(t,n)=>{let r=n?.frag,i=zt(r?.type);if(r&&e.isActive(i))for(let t of Bt(p,r))e.prefetch(t.url,i,t.kind)}),p.on(c.default.Events.KEY_LOADED,(t,n)=>e.keyUsable(zt(n?.frag?.type)))}p.on(c.default.Events.KEY_LOADED,()=>{u&&!this.reportedDrmReady&&(this.reportedDrmReady=!0,l({type:`drmReady`}))}),this.endWatchdog&&clearInterval(this.endWatchdog),this.endWatchdog=setInterval(()=>{this.checkEndStale(),this.checkStarvation(),this.updateCatchUpBand(),this.checkFutileChase(),this.adaptHoldBack(),this.checkFrameDrops()},Zt),p.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>{this.renditionSwitches+=1;let n=this.lastLevelIndex>=0?p.levels[this.lastLevelIndex]:void 0,r=p.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(),l({type:`qualitychange`,index:t.level})}),p.on(c.default.Events.AUDIO_TRACK_SWITCHED,(e,t)=>l({type:`audiotrackchange`,id:t.id})),p.on(c.default.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>l({type:`texttrackchange`,id:t.id})),p.on(c.default.Events.ERROR,(e,t)=>this.onError(t)),p.loadSource(t.manifestUrl),p.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(t){if(e==null)this.bitrateCapLevel=-1;else{let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),this.bitrateCapLevel=n}this.pushCap()}}computeSizeCapTarget(){let e=this.hls;if(!e||e.levels.length===0)return null;let{video:t}=this.deps,n=t.getBoundingClientRect(),r=n.width,i=n.height;if(!r&&!i&&(r=t.width||0,i=t.height||0),!(r>0)||!(i>0))return null;let a=e.config??{},o=typeof self<`u`&&self.devicePixelRatio>0?self.devicePixelRatio:1,s=a.ignoreDevicePixelRatio?1:o;s=Math.min(s,a.maxDevicePixelRatio??1/0);let l=c.CapLevelController.getMaxLevelByMediaSize(e.levels,r*s,i*s),u=this.deps.sizeCapHeadroom;if(u==null&&o>=_n)return l;let d=u??gn,f=Number.isNaN(d)?gn:d===1/0?e.levels.length:Math.max(0,Math.floor(d));return vn(e.levels,l,f)}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?mn:hn;this.capTimer=setTimeout(()=>{this.capTimer=null,this.computeSizeCapTarget()===e?this.applySizeCap():this.onMediaResize()},t)}measureLadder(e){let t=e.levels.map(e=>e.height).filter(e=>!!e);this.ladderHeights=t.length?[...new Set(t)].sort((e,t)=>e-t):void 0,this.ladderTopBitrateKbps=e.levels.length?Math.round(Math.max(...e.levels.map(e=>e.bitrate))/1e3):0}dropLevelsWidevineCannotPlay(e){this.removeLevelsWhere(e,e=>Qe(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&z(e)!==`avc`&&!!z(e)));for(let n of t)Xe(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&&z(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:!z(e.videoCodec)||Qe(e.videoCodec)===!0))return console.warn(`havik-player: every rendition is ${a}, which Widevine may not play on this browser; keeping them`),!1;for(let t=r.length-1;t>=0;--t)e.removeLevel(r[t]);return console.info(`havik-player: skipped ${r.length} rendition(s) Widevine cannot play on this browser (${a})`),!0}applySizeCap(){if(!this.sizeCapManaged)return;this.capTimer&&=(clearTimeout(this.capTimer),null);let e=this.computeSizeCapTarget();e!=null&&(this.sizeCapLevel=e,this.pushCap())}pushCap(){let e=this.hls;if(!e)return;let t=[[`size`,this.sizeCapLevel??-1],[`bitrate`,this.bitrateCapLevel],[`fps`,this.fpsCapLevel(e)]],n=-1,r=null;for(let[e,i]of t)i>=0&&(n<0||i<n)&&(n=i,r=e);e.autoLevelCapping=n,this.pushedCapLevel=n,this.pushedCapReason=r}getAudioTracks(){return this.hls?this.hls.audioTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0,default:!!e.default})):[]}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}getTextTracks(){return this.hls?this.hls.subtitleTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0})):[]}setTextTrack(e){let t=this.hls;t&&(e<0?(t.subtitleTrack=-1,t.subtitleDisplay=!1):(t.subtitleTrack=e,t.subtitleDisplay=!0))}seekToLive(){let e=this.hls;e&&typeof e.liveSyncPosition==`number`&&(this.deps.video.currentTime=e.liveSyncPosition)}setLicenseUrls(e){e.widevine&&(this.licenseUrl=e.widevine)}getStats(){let e=this.hls,t=this.frameCounter.read(),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames,lowLatency:this.detectedLowLatency,bytesLoaded:this.bytesLoaded,playlistBytesLoaded:this.playlistBytesLoaded,renditionSwitches:this.renditionSwitches,liveRetargets:this.liveRetargets,holdBackSteps:this.holdBackSteps,fpsDownCaps:this.fpsDownCaps,licenseTimeMs:this.licenseTimeMs,upshifts:this.upshifts,downshifts:this.downshifts,requestCount:this.requestCount,requestErrors:this.requestErrors,requestTimesMs:[...this.requestTimesMs],ladderHeights:this.ladderHeights,ladderTopBitrateKbps:this.ladderTopBitrateKbps||void 0};if(this.cdnHost&&(n.cdnHost=this.cdnHost),this.licenseRequested&&(n.keySystem=`widevine`,n.drmSecurityLevel=`L3`),e){n.qualityPinned=!e.autoLevelEnabled,typeof e.latency==`number`&&(n.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(n.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(n.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let t=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;t&&(n.levelHeight=t.height);let r=e.autoLevelCapping,i=r>=0?e.levels[r]:void 0;if(i&&i.height>0){n.maxLevelHeight=i.height;let t=e.config??{};t.capLevelToPlayerSize!==!0&&t.capLevelOnFPSDrop!==!0&&r===this.pushedCapLevel&&this.pushedCapReason&&(n.capReason=this.pushedCapReason)}t?.videoCodec&&(n.videoCodec=t.videoCodec),t?.audioCodec&&(n.audioCodec=t.audioCodec),t&&typeof t.bitrate==`number`&&(n.renditionBitrateKbps=Math.round(t.bitrate/1e3)),typeof t?.details?.live==`boolean`&&(n.isLive=t.details.live,typeof e.liveSyncPosition==`number`&&(n.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return n}trackEnd(e){let t=e.details;if(t){if(t.live===!0){let e=!this.sawLive;this.sawLive=!0,e&&this.applyHoldBackPrior();let n=t.endSN??-1;n!==this.lastEndSN&&(this.lastEndSN=n,this.lastAdvanceMs=Date.now(),this.chaseSuspended&&this.resumeChasing());return}this.sawLive&&this.emitEnded(`endlist`)}}checkEndStale(){if(this.endedEmitted||!this.sawLive||this.lastAdvanceMs===0)return;if(typeof document<`u`&&document.hidden){this.lastAdvanceMs=Date.now();return}if(this.loadSuspended){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>$t&&this.suspendChasing(),e>Xt&&this.emitEnded(`stalled`)}resetStarvationWindow(){this.starvedTicks=0,this.deadTicks=0,this.mainFragsSinceTick=0,this.recentMainFrags=[]}clearKick(){this.kickPending=!1,this.kickTicks=0,this.kickKind=null}checkStarvation(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended)return;if(typeof document<`u`&&document.hidden||this.loadSuspended){this.resetStarvationWindow();return}let n=Date.now(),r=this.lastAdvanceMs!==0&&n-this.lastAdvanceMs<$t,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>sn,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=H(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>fn&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=un&&(this.clearKick(),this.starvationRebuilds<dn)){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>=cn,d=!i&&this.deadTicks>=fn&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=pn;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=ln))){this.starvationKicks+=1,this.kickPending=!0,this.kickTicks=0,this.kickKind=d?`dead`:`quiet`,this.clearRecoveryReset(),console.warn(d?`havik-player: video starved while hls.js keeps loading media it never plays (dead pipeline at the live edge) — restarting the load`:`havik-player: video starved while the live playlist advances (wedged hls.js fragment pipeline) — restarting the load`);try{e.stopLoad(),e.startLoad(-1)}catch(e){console.warn(`havik-player: starvation kick failed`,e)}}}updateCatchUpBand(){let e=this.hls;if(!e||this.catchUpRate<=1||this.chaseSuspended||this.loadSuspended)return;let t=e.latency,n=e.targetLatency;if(typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t))return;let r=t-n;!this.catchUpEngaged&&r>en?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=en&&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=Sn,this.fpsBadTicks=0)}resetFrameDropWindow(){this.fpsLastFrames=-1,this.fpsLastDropped=-1,this.fpsBadTicks=0}checkFrameDrops(){let e=this.hls,{video:t}=this.deps;if(!e||!this.fpsCapManaged||this.loadSuspended||t.paused||!e.autoLevelEnabled||typeof document<`u`&&document.hidden){this.resetFrameDropWindow();return}let{totalFrames:n,dropped:r}=H(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<bn||o<0){this.fpsBadTicks=0;return}if(this.fpsGraceTicks>0){--this.fpsGraceTicks,this.fpsBadTicks=0;return}if(o<=yn*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<xn)return;this.fpsBadTicks=0;let s=e.levels,c=s[e.currentLevel];if(!c)return;let l=s.filter(e=>e.height>0&&e.height<c.height),u=(l.length?l:s.filter(e=>e.bitrate<c.bitrate)).map(e=>e.bitrate).sort((e,t)=>t-e)[0];u!=null&&(this.fpsCapBitrate!=null&&u>=this.fpsCapBitrate||(this.fpsCapBitrate=u,l.length&&(this.fpsCapFailedHeight=c.height),this.fpsDownCaps+=1,console.warn(`havik-player: dropping ${Math.round(100*o/a)}% of frames at ${c.height}p — capping quality below it`),this.pushCap()))}resetChaseWindow(){this.chaseLatency=-1,this.chaseTicks=0}checkFutileChase(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||typeof document<`u`&&document.hidden){this.resetChaseWindow();return}let n=e.latency,r=t.playbackRate,i=e.config.maxLiveSyncPlaybackRate;if(!(!t.paused&&typeof i==`number`&&i>1&&r>=Math.min(rn,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=nn){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<tn)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+an||(console.warn(`havik-player: catch-up at ${r}x not gaining on the live edge (latency ${n.toFixed(1)}s); holding at ${s.toFixed(1)}s`),this.liveRetargets+=1,e.targetLatency=s,this.deps.emit({type:`livetargetchange`,change:{targetSeconds:s,previousSeconds:o,reason:`futile-chase`}}))}armHoldBack(e,t){this.holdBackEnabled&&(this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[],this.holdBackBase<0&&typeof t.liveSyncDuration==`number`&&(this.holdBackBase=t.liveSyncDuration),this.holdBackApplied>0&&(e.targetLatency=this.holdBackApplied))}applyHoldBackPrior(){let e=this.hls;if(!this.holdBackEnabled||this.holdBackPriorChecked||!e||(this.holdBackPriorChecked=!0,this.holdBackApplied>0||this.holdBackStepCount>0))return;let t=e.targetLatency;if(this.holdBackBase<0&&typeof t==`number`&&t>0&&(this.holdBackBase=t),this.holdBackBase<0)return;let n=In();if(!(n>=Fn))return;let r=typeof t==`number`&&t>0?t:this.holdBackBase,i=Math.min(this.holdBackCeiling(e),this.holdBackBase+X);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:Pn,r=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;return r>1?Math.min(n,r-1):n}sampleHoldBack(e){if(!this.holdBackEnabled||typeof document<`u`&&document.hidden)return;let t=e.frag?.type;if(t!==`main`&&t!==`audio`)return;let n=e.part?e.part.duration:this.detectedLowLatency?0:e.frag?.duration;if(typeof n!=`number`||!(n>0))return;let r=(e.part??e.frag)?.stats?.loading;if(!r||!(r.start>0)||!(r.end>0))return;let i=r.first>r.start?r.first:r.end,a=Math.max(0,i-r.start)/(n*1e3);this.holdBackSamples.push({t:Date.now(),ratio:a}),this.holdBackSamples.length>256&&this.holdBackSamples.shift()}adaptHoldBack(){if(!this.holdBackEnabled)return;let e=this.hls;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||typeof document<`u`&&document.hidden){this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[];return}let t=Date.now(),n=t-Dn,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<On){this.holdBackSlowTicks=0;return}let c=r.map(e=>e.ratio).sort((e,t)=>e-t),l=Y(c,95),u=Y(c,50),d=Math.round(l*1e3);if(l>=kn&&u>=An){if(this.holdBackFastSince=0,this.holdBackSlowTicks+=1,this.holdBackSlowTicks<Mn)return;this.holdBackSlowTicks=0;let t=Math.ceil((s-o)/X),n=Math.ceil((a-o)/X-1e-9);if(n>this.holdBackStepCount&&(this.holdBackStepCount=n),this.holdBackStepCount>=t)return;this.holdBackStepCount+=1;let r=Math.min(s,o+this.holdBackStepCount*X);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>=jn){this.holdBackFastSince=0;return}if(this.holdBackFastSince===0){this.holdBackFastSince=t;return}if(t-this.holdBackFastSince<Nn||(this.holdBackFastSince=t,this.holdBackStepCount===0||a!==this.holdBackApplied))return;--this.holdBackStepCount;let f=Math.max(o,o+this.holdBackStepCount*X);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?Ht:Be()??Ht}maybeRememberBandwidth(e){if(this.deps.rememberBandwidth===!1||this.bwFragsLoaded<Ut)return;let t=Date.now();if(!e&&t-this.bwSavedAt<Wt)return;let n=this.hls?.bandwidthEstimate;typeof n!=`number`||!Number.isFinite(n)||n<=0||(this.bwSavedAt=t,Ve(n))}destroy(){if(this.maybeRememberBandwidth(!0),this.detachFrames?.(),this.detachFrames=null,this.prefetch?.destroy(),this.prefetch=null,this.clearRecoveryReset(),this.capTimer&&=(clearTimeout(this.capTimer),null),this.capObserver&&=(this.capObserver.disconnect(),null),this.unwatchDprChanges(),this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onSeeking&&=(this.deps.video.removeEventListener(`seeking`,this.onSeeking),null),this.onTimeUpdate&&=(this.deps.video.removeEventListener(`timeupdate`,this.onTimeUpdate),null),this.onPause&&=(this.deps.video.removeEventListener(`pause`,this.onPause),null),this.onPlay&&=(this.deps.video.removeEventListener(`play`,this.onPlay),null),this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),this.licenseRetryTimer&&=(clearTimeout(this.licenseRetryTimer),null),this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during teardown`,e)}this.hls=null}}clearRecoveryReset(){this.recoveryResetTimer&&=(clearTimeout(this.recoveryResetTimer),null)}scheduleLicenseRetry(e){if(e.details!==c.default.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED&&e.details!==c.default.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>=qt)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{this.licenseRetryTimer=null,this.rebuildInstance(`license retry`)},n),!0}rebuildInstance(e){if(this.hls){try{this.hls.destroy()}catch(t){console.warn(`havik-player: hls.js destroy() threw during ${e}`,t)}this.hls=null,this.startHls(),this.armFrameDropGrace()}}onError(e){if(e.type===c.default.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===c.default.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===c.default.ErrorTypes.NETWORK_ERROR){if(this.networkRecoveries<Kt){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===c.default.ErrorTypes.MEDIA_ERROR){if(this.mediaRecoveries<Gt){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??``,a=t===`DRM`&&n===403&&e.details===c.default.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED?d(jt(e.networkDetails)):void 0;return new l(t===`DRM`?f(n,a):n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`,a?{serverCode:a}:void 0)}},Bn=15e3,Vn=6e5,Hn=3e5,Un=100,Z=1,Wn=1e3,Gn=3e4,Kn=1e3,qn={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},Jn={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`},Yn=new Set([`INVALID_URN`,`NOT_FOUND`,`GEO_DENIED`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),Q={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 Xn(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 Zn=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),Qn=new Set,$n=new Set,er=new Set,tr=e=>`this page's Content-Security-Policy blocks QoE beacons. Add ${e} to connect-src; until then none are sent.`;function nr(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(Qn.has(t)&&!$n.has(t)){$n.add(t),b(tr(new URL(t).origin));for(let e of er)e.noteCspBlocked()}}function rr(e,t){return b(t,e),{disabledReason:t}}function ir(e,t,n){if(n)return t&&!Zn(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return rr(`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=Xn(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return rr(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 ar=class{opts;url;cspKey;now;seq=0;pending=[];timer=null;endedFlag=!1;lastBytes=0;lastPlaylistBytes=0;lastDropped=0;lastSwitches=0;playingSinceMs=null;hiddenSinceMs=null;playingTotalMs=0;hiddenTotalMs=0;lastHbPlayingMs=0;lastHbHiddenMs=0;lastHbRebufferMs=0;lastHbRebufferCount=0;lastHbActiveMs=0;rebufferCount=0;rebufferTotalMs=0;bufferingSinceMs=null;isBuffering=!1;errorCount=0;seekCount=0;pauseCount=0;isPlaying=!1;isHidden=!1;isMuted=!1;activeSinceMs=null;activeTotalMs=0;mutedSinceMs=null;mutedTotalMs=0;lastHbMutedMs=0;volumeChanges=0;muteChanges=0;presentation=`inline`;presentationSinceMs;fullscreenTotalMs=0;pipTotalMs=0;waitingSinceMs=null;waitingTotalMs=0;firstAudioMs=0;timeToFirstStallMs=0;lastStallMs=0;lastErrorMs=0;lastSeekMs=-1;stallIsSeekInduced=!1;lastErrorStage=null;sawFirstBytes=!1;mediaInfoSignature=``;lastUpshifts=0;lastDownshifts=0;lastDecoded=0;lastRequestCount=0;lastRequestErrors=0;pendingStart=null;firstFlushTimer=null;idleTimer=null;lastTickMs=0;bornMs;startupAnchorMs;startupTimeMs=0;manifestLoadMs=0;firstFragLoadMs=0;firstPlaylistMs=0;drmSetupMs=0;onPagehide=()=>this.end(`END_REASON_PAGEHIDE`);cspBlockedNoted=!1;onFreeze=()=>{this.endedFlag||this.flush(!0)};onResume=()=>this.checkSuspension(this.now());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())};constructor(e){this.opts={...e,heartbeatMs:e.heartbeatMs??Bn,idleMs:e.idleMs??Vn},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(),Wn),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&&Qn.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,nr),er.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,Hn);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(Z,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(Z,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(Z,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:Q[e]??`PLAYER_STATE_UNSPECIFIED`,toState:Q[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:qn[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<Kn}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(Z,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=Z),this.firstPlaylistMs>0&&(this.firstPlaylistMs=Z),this.firstFragLoadMs>0&&(this.firstFragLoadMs=Z),this.drmSetupMs>0&&(this.drmSetupMs=Z))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(Z,this.now()-this.startupAnchorMs))}noteFirstPlaylist(){this.firstPlaylistMs===0&&(this.firstPlaylistMs=Math.max(Z,this.now()-this.startupAnchorMs))}noteDrmReady(){this.drmSetupMs===0&&(this.drmSetupMs=Math.max(Z,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(Z,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(Yn.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=Q[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=Y(n,50),o.requestTimeP95Ms=Y(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=Jn[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,er.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<=Gn&&(i.abandonAfterStallMs=Math.max(Z,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=Gn&&(i.abandonAfterErrorMs=Math.max(Z,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?.(tr(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&$n.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>Un;){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 or(){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 sr(){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 cr(){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 lr(e){let t=or(),n={deviceClass:sr(),integration:t.integration,...cr()};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 ur(){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 dr=`2.23.2`,fr={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`},pr={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 mr(e,t){let n={...fr,...t};for(let t of Object.keys(pr))e.style.setProperty(pr[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var hr=`havik-player-styles`,gr=`
|
|
4
4
|
.havik-player{position:relative;display:block;width:100%;background:var(--havik-bg,#0e0f13);
|
|
5
5
|
color:var(--havik-text,#fff);font-family:var(--havik-font,system-ui,sans-serif);
|
|
6
6
|
overflow:hidden;line-height:1.4;-webkit-tap-highlight-color:transparent}
|