@oddin-gg/havik-player 2.16.10 → 2.16.12
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.js +24 -23
- package/dist/index.js.map +1 -1
- package/docs/API.md +5 -0
- 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;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,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 503:return`UNAVAILABLE`;default:return`INTERNAL`}}function d(e){return e===401?`UNAUTHORIZED`:e===403?`FORBIDDEN`:`DRM_CLIENT`}var f=new Set([`TOO_EARLY`,`UNAVAILABLE`,`RATE_LIMITED`,`NETWORK`]);function p(e){return f.has(e)}async function m(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 h(e){return e===`live`||e===`ended`||e===`upcoming`||e===`pending`?e:`upcoming`}function g(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`&&_(n.logoUrl)&&(i.logoUrl=n.logoUrl),t.push(i)}return t.length>0?t:void 0}function _(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 ee(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 m(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: ${te(e)}`,{cause:e})}}function te(e){return e instanceof Error?e.message:String(e)}var ne=new Set;function b(e,t=e){ne.has(t)||(ne.add(t),console.warn(`havik-player: ${e}`))}var re=1e3,ie=3e4,ae=6e5,oe=3e5,se=1e3,ce={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function le(e){let t=e===!0||e===!1?{}:e,n=Math.max(se,t.floorMs??re),r=Math.max(n,t.ceilMs??ie),i=Math.max(0,t.imminentMs??ae),a=Math.max(r,t.sanityFloorMs??oe);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:ue(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function ue(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 de(e,t,n){return Math.min(n,Math.max(t,e))}function fe(e){return Math.round(e*(1+.15*Math.random()))}function pe(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:de(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 me(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 he(e,t,n){let r=le(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)||!p(e.code))throw e;o+=1,e.liveStartsAtMs!=null&&Number.isFinite(e.liveStartsAtMs)&&(s=e.liveStartsAtMs);let t=Date.now(),c=pe(e.retryAfterMs,t,r,s),u=c.ttkMs,d=c.delay;if(r.jitter&&(d=fe(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:ce[e.code]??`unavailable`,retryInMs:d,attempt:o,elapsedMs:t-i,ttkMs:u}),await me(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 ge(t);return ye(await t.json(),e.matchUrn)}function S(e){let t=()=>x(e);return e.waitForLive?he(t,e.waitForLive,e.signal):t()}async function ge(e){let t=ee(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;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)}}catch{}return new l(u(e.status),e.status,r,{retryAfterMs:t,requestId:n,serverCode:i,liveStartsAtMs:a})}var _e=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 ve(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 ye(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=ve(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))_e.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}function be(e){return e.ownerDocument??document}function xe(e){return e.fullscreenElement??e.webkitFullscreenElement??null}function w(e,t){let n=xe(be(e));return n!=null&&(n===e||t!=null&&n===t)||e.webkitDisplayingFullscreen===!0}async function T(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 E(e,t){let n=e;if(n.webkitDisplayingFullscreen){n.webkitExitFullscreen?.();return}let r=be(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:h(e.status),statusRaw:e.status,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r,teams:g(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:h(e.status),statusRaw:e.status,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r,teams:g(e.teams)}))}}function Ee(e){return e.tournaments.flatMap(e=>e.matches)}var De=new Set([`NOT_FOUND`,`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=h(t.status),r=typeof t.status==`string`?t.status:n,s=g(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 D(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=>{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 m(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 O(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var k=`havik.player.deviceId`,A;function j(){if(A)return A;try{let e=globalThis.localStorage?.getItem(k);if(e)return A=e,e}catch{}let e=je();A=e;try{globalThis.localStorage?.setItem(k,e)}catch{}return e}function Ae(){A=void 0;try{globalThis.localStorage?.removeItem(k)}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??j(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var M=new WeakMap;function Ne(e,t){let n=M.get(e);n||(n=new Map,M.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 N(){return typeof navigator<`u`&&typeof navigator.requestMediaKeySystemAccess==`function`}var P=[`SW_SECURE_DECODE`,`SW_SECURE_CRYPTO`];function Pe(e){return e.startsWith(`com.widevine`)}function F(e,t){if(!Pe(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=P.indexOf(e.robustness);return n===-1||P.indexOf(t)>n})},r=P.flatMap(e=>t.filter(t=>n(t,e)).map(t=>({...t,videoCapabilities:t.videoCapabilities?.map(t=>({...t,robustness:e}))})));return[...t,...r]}function Fe(e){return(t,n)=>N()?navigator.requestMediaKeySystemAccess(t,F(t,n)).then(t=>({keySystem:t.keySystem,getConfiguration:()=>t.getConfiguration(),createMediaKeys:()=>Ne(e,t)})):Promise.reject(Error(`navigator.requestMediaKeySystemAccess is unavailable — EME needs a secure context (https, or localhost)`))}var I={video:`SW_SECURE_DECODE`,audio:`SW_SECURE_CRYPTO`,scheme:`cbcs`};function Ie(e){if(!N())return;let t=(e,t)=>({contentType:e,robustness:t,encryptionScheme:I.scheme});Fe(e)(`com.widevine.alpha`,[{initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],audioCapabilities:[t(`audio/mp4; codecs="mp4a.40.2"`,I.audio)],videoCapabilities:[t(`video/mp4; codecs="avc1.42e01e"`,I.video)]}]).then(e=>e.createMediaKeys()).catch(()=>{})}function L(e){let t=R(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 R(e){return(e??``).trim().toLowerCase()}var Le={hevc:`hvc1.1.6.L93.90`,dv:`dvh1.05.06`,av1:`av01.0.05M.08`,vp9:`vp09.00.10.08`},Re=new Map,z=new Map;function ze(e){let t=R(e),n=Re.get(t);if(n)return n;let r={initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],videoCapabilities:[{contentType:`video/mp4; codecs="${e.trim()}"`,robustness:I.video,encryptionScheme:I.scheme}]},i=(async()=>{try{return await navigator.requestMediaKeySystemAccess(`com.widevine.alpha`,F(`com.widevine.alpha`,[r])),!0}catch{return!1}})().then(e=>(z.set(t,e),e));return Re.set(t,i),i}function Be(){if(N())for(let e of Object.values(Le))ze(e)}function Ve(e){let t=L(e);if(t)return t===`avc`?!0:z.get(R(e))??z.get(R(Le[t]))}var He=5e3,Ue=`video/mp4; codecs="avc1.42E01E"`,We=`audio/mp4; codecs="mp4a.40.2"`,Ge={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function Ke(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:Ue,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:We,robustness:``,encryptionScheme:`cbcs`}]}]:F(`com.widevine.alpha`,[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:Ue,robustness:I.video,encryptionScheme:I.scheme}],audioCapabilities:[{contentType:We,robustness:I.audio,encryptionScheme:I.scheme}]}])}function qe(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 Je(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??He,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=Ge[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 qe((await qe(i(n,Ke(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 Ye=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function Xe(e){return Ye.test(e)}var Ze={integration:`https://feed-dev.oddin-video.gg`,production:`https://feed.oddin-video.gg`};function Qe(e){let t=Object.prototype.hasOwnProperty.call(Ze,e)?Ze[e]:void 0;if(!t)throw new l(`INTERNAL`,0,`unknown env ${JSON.stringify(e)} — expected 'integration' or 'production'`);return t}var $e={droppedFrames:0};function et(e){try{return new URL(e).host}catch{return``}}var tt=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function nt(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`||tt.test(i.name))&&i.startTime>=n){let e=et(i.name);e&&(t=e,n=i.startTime)}return t}function B(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var rt=class{video;baseFrames=0;baseDropped=0;lastFrames=0;lastDropped=0;constructor(e){this.video=e}read(){let e=B(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 it(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 at=2e3,ot=3,V=500,st=6e3,ct=.25,lt=250,ut=.05,dt=4;function ft(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 H(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function U(){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 pt(){if(typeof navigator>`u`||!U())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var W=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;fairplayKeyIV;loadStarted;preloadTouched=!1;savedPreload=null;cdnHost=``;builtAt;frameCounter;detachFrames=null;constructor(e){this.deps=e,this.frameCounter=new rt(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.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=ht(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)=>a({type:`error`,error:new l(d(t),t,e),fatal:n});this.onEncrypted=a=>{let c=a;c.initData&&!this.fairplayArmed&&(this.fairplayArmed=!0,this.fairplayKeyIV=ft(c.initData),(async()=>{try{let a=await(await navigator.requestMediaKeySystemAccess(`com.apple.fps`,[{initDataTypes:[c.initDataType],videoCapabilities:[{contentType:`application/vnd.apple.mpegurl`,robustness:``}],distinctiveIdentifier:`not-allowed`,persistentState:`not-allowed`,sessionTypes:[`temporary`]}])).createMediaKeys(),l=await fetch(o.certificateUrl,{headers:{"x-api-key":n.apiKey}});if(!l.ok){this.fairplayArmed=!1,s(`FairPlay certificate request failed: ${l.status}`,l.status,!0);return}await a.setServerCertificate(await l.arrayBuffer()),await e.setMediaKeys(a);let u=a.createSession();this.keySession=u,u.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){s(`FairPlay license request failed: ${a.status}`,a.status,!0);return}await u.update(new Uint8Array(await a.arrayBuffer()))}catch(e){s(`FairPlay license request failed: ${String(e)}`,0,!0)}})()}),await u.generateRequest(c.initDataType,c.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||=nt(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<=dt,!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=G();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=at&&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=G,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=V;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+ct),s=Math.max(r,t()-n)>=st;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,V)};this.refocusTimer=setTimeout(i,V)}cancelRefocus(){this.refocusTimer!=null&&clearTimeout(this.refocusTimer),this.refocusTimer=null}watchBufferedEnd(){if(this.edgeTimer!=null)return;let{video:e}=this.deps;this.onEdgeReset=()=>{this.lastBufferedEnd=null,this.bufferedAdvancedAt=null},e.addEventListener(`seeking`,this.onEdgeReset),e.addEventListener(`emptied`,this.onEdgeReset),this.edgeTimer=setInterval(()=>{if(e.duration!==1/0)return;let t=mt(e,e.currentTime);t!=null&&((this.lastBufferedEnd==null||Math.abs(t-this.lastBufferedEnd)>=ut)&&(this.bufferedAdvancedAt=G()),this.lastBufferedEnd=t)},lt)}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.lastBufferedEnd=null,this.bufferedAdvancedAt=null}liveEdgeEstimate(){let e=this.deps.video;if(e.duration!==1/0)return null;let t=this.liveEnd(),n=mt(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,(G()-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-ot,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 G(){return typeof performance<`u`?performance.now():Date.now()}function mt(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 ht(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function K(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 gt=15e3,_t=5e3,vt=6;function yt(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var bt=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=yt(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;if(i>=vt)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)},gt)}take(e){let t=yt(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 xt(e){let t=c.default.DefaultConfig?.loader;if(typeof t!=`function`)return;class n extends t{served=!1;cancelled=!1;stats=St();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||_t,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 St(){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 q(e){return e===`audio`?`audio`:`main`}function Ct(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 wt(){return c.default.isSupported()}var Tt=3,Et=5,Dt=3,Ot=1e4,kt=3e4,At=12e3,jt=3e3,Mt=.02,Nt=6e3,Pt=.5,Ft=3,It=.5,Lt=1.1,Rt=.25,zt=5e3,Bt=4e3,Vt=2,Ht=5,Ut=2,Wt=2,Gt=4,Kt=4,qt=2e3,Jt=3e4,Yt=.2,Xt=30,Zt=2,Qt=2,$t=9,en=.5,tn=64;function nn(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Qt;let t=Math.max(12,e.liveSyncDuration+$t);(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 an=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;recentMainFrags=[];chaseSuspended=!1;savedLiveMaxLatency;savedMaxSyncRate;chaseLatency=-1;catchUpRate=1;catchUpEngaged=!1;onTimeUpdate=null;chaseTicks=0;liveRetargets=0;capObserver=null;capTimer=null;sizeCapLevel=null;bitrateCapLevel=-1;fpsCapBitrate=null;fpsCapFailedHeight=null;fpsCapManaged=!0;fpsLastFrames=-1;fpsLastDropped=-1;fpsBadTicks=0;fpsDownCaps=0;sizeCapManaged=!0;dprMedia=null;onDprChange=null;loadStarted;frameCounter;detachFrames=null;constructor(e){this.deps=e,this.frameCounter=new rt(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=H(n)&&U(),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&&(Ie(n),Be()),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}},zt))}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+en||(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)<Mt)){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={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,maxBufferHole:.5,maxLiveSyncPlaybackRate:1.1,abrEwmaDefaultEstimate:1e6,capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...u?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:I.video,audioRobustness:I.audio,videoEncryptionScheme:I.scheme,audioEncryptionScheme:I.scheme},...N()?{requestMediaKeySystemAccessFunc:Fe(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||!K(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),Ot)});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&&!d.fLoader){let e=new bt({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=xt(e);n&&(this.prefetch=e,d.fLoader=n)}nn(d),this.catchUpRate=typeof d.maxLiveSyncPlaybackRate==`number`?d.maxLiveSyncPlaybackRate:1,this.catchUpEngaged=!1,this.catchUpRate>1&&(d.maxLiveSyncPlaybackRate=1),this.sizeCapManaged=d.capLevelToPlayerSize!==!0,this.fpsCapManaged=!(s&&`capLevelOnFPSDrop`in s),this.loadStarted=d.autoStartLoad!==!1;let f=new c.default(d);if(this.hls=f,f.on(c.default.Events.FRAG_PARSED,(e,t)=>this.reanchorPartTimeline(f,t)),f.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,u&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&this.dropLevelsWidevineCannotPlay(f),this.measureLadder(f),this.applySizeCap(),this.loadSuspended=!1,e.paused&&this.schedulePauseSuspend(),l({type:`ready`})}),f.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},kt)))}),f.on(c.default.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),f.on(c.default.Events.FRAG_LOADED,(e,t)=>{t?.frag?.type===`main`&&(this.mainFragsSinceTick+=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>tn&&this.requestTimesMs.shift());let a=t?.frag?.url;if(a){let e=et(a);e&&(this.cdnHost=e)}}),f.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}))}),f.on(c.default.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.prefetch){let e=this.prefetch;f.on(c.default.Events.KEY_LOADING,(t,n)=>{let r=n?.frag,i=q(r?.type);if(r&&e.isActive(i))for(let t of Ct(f,r))e.prefetch(t.url,i,t.kind)}),f.on(c.default.Events.KEY_LOADED,(t,n)=>e.keyUsable(q(n?.frag?.type)))}f.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.checkFrameDrops()},jt),f.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>{this.renditionSwitches+=1;let n=this.lastLevelIndex>=0?f.levels[this.lastLevelIndex]:void 0,r=f.levels[t.level];n&&r&&r.bitrate!==n.bitrate&&(r.bitrate>n.bitrate?this.upshifts+=1:this.downshifts+=1),this.lastLevelIndex=t.level,l({type:`qualitychange`,index:t.level})}),f.on(c.default.Events.AUDIO_TRACK_SWITCHED,(e,t)=>l({type:`audiotrackchange`,id:t.id})),f.on(c.default.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>l({type:`texttrackchange`,id:t.id})),f.on(c.default.Events.ERROR,(e,t)=>this.onError(t)),f.loadSource(t.manifestUrl),f.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(t){if(e==null)this.bitrateCapLevel=-1;else{let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),this.bitrateCapLevel=n}this.pushCap()}}computeSizeCapTarget(){let e=this.hls;if(!e||e.levels.length===0)return null;let{video:t}=this.deps,n=t.getBoundingClientRect(),r=n.width,i=n.height;if(!r&&!i&&(r=t.width||0,i=t.height||0),!(r>0)||!(i>0))return null;let a=e.config??{},o=1;return!a.ignoreDevicePixelRatio&&typeof self<`u`&&self.devicePixelRatio>0&&(o=self.devicePixelRatio),o=Math.min(o,a.maxDevicePixelRatio??1/0),c.CapLevelController.getMaxLevelByMediaSize(e.levels,r*o,i*o)}onMediaResize(){if(!this.sizeCapManaged)return;let e=this.computeSizeCapTarget();if(e==null)return;if(this.sizeCapLevel==null){this.applySizeCap();return}if(e===this.sizeCapLevel){this.capTimer&&=(clearTimeout(this.capTimer),null);return}this.capTimer&&clearTimeout(this.capTimer);let t=e>this.sizeCapLevel?qt:Jt;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=>Ve(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&L(e)!==`avc`&&!!L(e)));for(let n of t)ze(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&&L(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:!L(e.videoCodec)||Ve(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=[this.sizeCapLevel??-1,this.bitrateCapLevel,this.fpsCapLevel(e)].filter(e=>e>=0);e.autoLevelCapping=t.length?Math.min(...t):-1}getAudioTracks(){return this.hls?this.hls.audioTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0,default:!!e.default})):[]}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}getTextTracks(){return this.hls?this.hls.subtitleTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0})):[]}setTextTrack(e){let t=this.hls;t&&(e<0?(t.subtitleTrack=-1,t.subtitleDisplay=!1):(t.subtitleTrack=e,t.subtitleDisplay=!0))}seekToLive(){let e=this.hls;e&&typeof e.liveSyncPosition==`number`&&(this.deps.video.currentTime=e.liveSyncPosition)}setLicenseUrls(e){e.widevine&&(this.licenseUrl=e.widevine)}getStats(){let e=this.hls,t=this.frameCounter.read(),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames,lowLatency:this.detectedLowLatency,bytesLoaded:this.bytesLoaded,playlistBytesLoaded:this.playlistBytesLoaded,renditionSwitches:this.renditionSwitches,liveRetargets:this.liveRetargets,fpsDownCaps:this.fpsDownCaps,licenseTimeMs:this.licenseTimeMs,upshifts:this.upshifts,downshifts:this.downshifts,requestCount:this.requestCount,requestErrors:this.requestErrors,requestTimesMs:[...this.requestTimesMs],ladderHeights:this.ladderHeights,ladderTopBitrateKbps:this.ladderTopBitrateKbps||void 0};if(this.cdnHost&&(n.cdnHost=this.cdnHost),this.licenseRequested&&(n.keySystem=`widevine`,n.drmSecurityLevel=`L3`),e){n.qualityPinned=!e.autoLevelEnabled,typeof e.latency==`number`&&(n.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(n.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(n.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let t=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;t&&(n.levelHeight=t.height),t?.videoCodec&&(n.videoCodec=t.videoCodec),t?.audioCodec&&(n.audioCodec=t.audioCodec),t&&typeof t.bitrate==`number`&&(n.renditionBitrateKbps=Math.round(t.bitrate/1e3)),typeof t?.details?.live==`boolean`&&(n.isLive=t.details.live,typeof e.liveSyncPosition==`number`&&(n.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return n}trackEnd(e){let t=e.details;if(t){if(t.live===!0){this.sawLive=!0;let e=t.endSN??-1;e!==this.lastEndSN&&(this.lastEndSN=e,this.lastAdvanceMs=Date.now(),this.chaseSuspended&&this.resumeChasing());return}this.sawLive&&this.emitEnded(`endlist`)}}checkEndStale(){if(this.endedEmitted||!this.sawLive||this.lastAdvanceMs===0)return;if(typeof document<`u`&&document.hidden){this.lastAdvanceMs=Date.now();return}if(this.loadSuspended){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>Nt&&this.suspendChasing(),e>At&&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<Nt,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>Bt,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=B(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>Gt&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=Ut&&(this.clearKick(),this.starvationRebuilds<Wt)){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>=Vt,d=!i&&this.deadTicks>=Gt&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=Kt;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=Ht))){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>Pt?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=Pt&&this.deps.video.playbackRate===1&&(this.catchUpEngaged=!1);let i=this.catchUpEngaged?this.catchUpRate:1;e.config.maxLiveSyncPlaybackRate!==i&&(e.config.maxLiveSyncPlaybackRate=i)}fpsCapLevel(e){if(this.fpsCapBitrate==null)return-1;let t=this.fpsCapFailedHeight,n=-1;return e.levels.forEach((e,r)=>{let i=t==null||!(e.height>0)||e.height<t;e.bitrate<=this.fpsCapBitrate&&i&&(n=r)}),n<0?0:n}resetFrameDropWindow(){this.fpsLastFrames=-1,this.fpsLastDropped=-1,this.fpsBadTicks=0}checkFrameDrops(){let e=this.hls,{video:t}=this.deps;if(!e||!this.fpsCapManaged||this.loadSuspended||t.paused||!e.autoLevelEnabled||typeof document<`u`&&document.hidden){this.resetFrameDropWindow();return}let{totalFrames:n,dropped:r}=B(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<Xt||o<0){this.fpsBadTicks=0;return}if(o<=Yt*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<Zt)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(Lt,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=It){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<Ft)return;this.resetChaseWindow();let a=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;if(!(a>1))return;let o=typeof e.targetLatency==`number`?e.targetLatency:0,s=Math.min(n,a-1);s<o+Rt||(console.warn(`havik-player: catch-up at ${r}x not gaining on the live edge (latency ${n.toFixed(1)}s); holding at ${s.toFixed(1)}s`),this.liveRetargets+=1,e.targetLatency=s)}suspendChasing(){let e=this.hls;if(!e)return;this.chaseSuspended=!0,this.savedLiveMaxLatency=e.config.liveMaxLatencyDuration,this.savedMaxSyncRate=e.config.maxLiveSyncPlaybackRate,e.config.liveMaxLatencyDuration=2**53-1,e.config.maxLiveSyncPlaybackRate=1;let{video:t}=this.deps,n=this.savedMaxSyncRate;t.playbackRate>1&&typeof n==`number`&&t.playbackRate<=n&&(t.playbackRate=1)}resumeChasing(){this.chaseSuspended=!1;let e=this.hls;e&&(e.config.liveMaxLatencyDuration=this.savedLiveMaxLatency,e.config.maxLiveSyncPlaybackRate=this.savedMaxSyncRate)}emitEnded(e){this.endedEmitted||(this.endedEmitted=!0,this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.deps.emit({type:`ended`,reason:e}))}stop(){this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.clearKick(),this.stopped=!0,this.loadSuspended=!1,this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null);try{this.hls?.stopLoad()}catch{}try{this.deps.video.pause()}catch{}}destroy(){if(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>=Dt)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{this.licenseRetryTimer=null,this.rebuildInstance(`license retry`)},n),!0}rebuildInstance(e){if(this.hls){try{this.hls.destroy()}catch(t){console.warn(`havik-player: hls.js destroy() threw during ${e}`,t)}this.hls=null,this.startHls()}}onError(e){if(e.type===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<Et){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<Tt){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??``;return new l(t===`DRM`?d(n):n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`)}},on=15e3,sn=6e5,cn=3e5,ln=100,J=1,un=1e3,dn=3e4,fn=1e3,pn={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},mn={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`};function hn(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}var gn=new Set([`INVALID_URN`,`NOT_FOUND`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),Y={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 _n(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 vn=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),yn=new Set,X=new Set,Z=new Set,bn=e=>`this page's Content-Security-Policy blocks QoE beacons. Add ${e} to connect-src; until then none are sent.`;function xn(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(yn.has(t)&&!X.has(t)){X.add(t),b(bn(new URL(t).origin));for(let e of Z)e.noteCspBlocked()}}function Sn(e,t){return b(t,e),{disabledReason:t}}function Cn(e,t,n){if(n)return t&&!vn(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return Sn(`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=_n(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return Sn(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 wn=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??on,idleMs:e.idleMs??sn},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(),un),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&&yn.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,xn),Z.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,cn);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(J,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(J,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(J,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:Y[e]??`PLAYER_STATE_UNSPECIFIED`,toState:Y[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:pn[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<fn}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(J,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=J),this.firstPlaylistMs>0&&(this.firstPlaylistMs=J),this.firstFragLoadMs>0&&(this.firstFragLoadMs=J),this.drmSetupMs>0&&(this.drmSetupMs=J))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(J,this.now()-this.startupAnchorMs))}noteFirstPlaylist(){this.firstPlaylistMs===0&&(this.firstPlaylistMs=Math.max(J,this.now()-this.startupAnchorMs))}noteDrmReady(){this.drmSetupMs===0&&(this.drmSetupMs=Math.max(J,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(J,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`)return`ERROR_STAGE_DRM`;if(gn.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=Y[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=hn(n,50),o.requestTimeP95Ms=hn(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=mn[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,Z.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<=dn&&(i.abandonAfterStallMs=Math.max(J,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=dn&&(i.abandonAfterErrorMs=Math.max(J,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?.(bn(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&X.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>ln;){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 Tn(){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 En(){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 Dn(){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 On(e){let t=Tn(),n={deviceClass:En(),integration:t.integration,...Dn()};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 kn(){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 An=`2.16.10`,jn={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`},Mn={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 Nn(e,t){let n={...jn,...t};for(let t of Object.keys(Mn))e.style.setProperty(Mn[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var Pn=`havik-player-styles`,Fn=`
|
|
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 m(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 O(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var k=`havik.player.deviceId`,A;function j(){if(A)return A;try{let e=globalThis.localStorage?.getItem(k);if(e)return A=e,e}catch{}let e=je();A=e;try{globalThis.localStorage?.setItem(k,e)}catch{}return e}function Ae(){A=void 0;try{globalThis.localStorage?.removeItem(k)}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??j(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var M=new WeakMap;function Ne(e,t){let n=M.get(e);n||(n=new Map,M.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 N(){return typeof navigator<`u`&&typeof navigator.requestMediaKeySystemAccess==`function`}var P=[`SW_SECURE_DECODE`,`SW_SECURE_CRYPTO`];function Pe(e){return e.startsWith(`com.widevine`)}function F(e,t){if(!Pe(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=P.indexOf(e.robustness);return n===-1||P.indexOf(t)>n})},r=P.flatMap(e=>t.filter(t=>n(t,e)).map(t=>({...t,videoCapabilities:t.videoCapabilities?.map(t=>({...t,robustness:e}))})));return[...t,...r]}function Fe(e){return(t,n)=>N()?navigator.requestMediaKeySystemAccess(t,F(t,n)).then(t=>({keySystem:t.keySystem,getConfiguration:()=>t.getConfiguration(),createMediaKeys:()=>Ne(e,t)})):Promise.reject(Error(`navigator.requestMediaKeySystemAccess is unavailable — EME needs a secure context (https, or localhost)`))}var I={video:`SW_SECURE_DECODE`,audio:`SW_SECURE_CRYPTO`,scheme:`cbcs`};function Ie(e){if(!N())return;let t=(e,t)=>({contentType:e,robustness:t,encryptionScheme:I.scheme});Fe(e)(`com.widevine.alpha`,[{initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],audioCapabilities:[t(`audio/mp4; codecs="mp4a.40.2"`,I.audio)],videoCapabilities:[t(`video/mp4; codecs="avc1.42e01e"`,I.video)]}]).then(e=>e.createMediaKeys()).catch(()=>{})}function L(e){let t=R(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 R(e){return(e??``).trim().toLowerCase()}var Le={hevc:`hvc1.1.6.L93.90`,dv:`dvh1.05.06`,av1:`av01.0.05M.08`,vp9:`vp09.00.10.08`},Re=new Map,z=new Map;function ze(e){let t=R(e),n=Re.get(t);if(n)return n;let r={initDataTypes:[`cenc`],distinctiveIdentifier:`optional`,persistentState:`optional`,sessionTypes:[`temporary`],videoCapabilities:[{contentType:`video/mp4; codecs="${e.trim()}"`,robustness:I.video,encryptionScheme:I.scheme}]},i=(async()=>{try{return await navigator.requestMediaKeySystemAccess(`com.widevine.alpha`,F(`com.widevine.alpha`,[r])),!0}catch{return!1}})().then(e=>(z.set(t,e),e));return Re.set(t,i),i}function Be(){if(N())for(let e of Object.values(Le))ze(e)}function Ve(e){let t=L(e);if(t)return t===`avc`?!0:z.get(R(e))??z.get(R(Le[t]))}var He=5e3,Ue=`video/mp4; codecs="avc1.42E01E"`,We=`audio/mp4; codecs="mp4a.40.2"`,Ge={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function Ke(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:Ue,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:We,robustness:``,encryptionScheme:`cbcs`}]}]:F(`com.widevine.alpha`,[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:Ue,robustness:I.video,encryptionScheme:I.scheme}],audioCapabilities:[{contentType:We,robustness:I.audio,encryptionScheme:I.scheme}]}])}function qe(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 Je(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??He,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=Ge[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 qe((await qe(i(n,Ke(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 Ye=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function Xe(e){return Ye.test(e)}var Ze={integration:`https://feed-dev.oddin-video.gg`,production:`https://feed.oddin-video.gg`};function Qe(e){let t=Object.prototype.hasOwnProperty.call(Ze,e)?Ze[e]:void 0;if(!t)throw new l(`INTERNAL`,0,`unknown env ${JSON.stringify(e)} — expected 'integration' or 'production'`);return t}var $e={droppedFrames:0};function et(e){try{return new URL(e).host}catch{return``}}var tt=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function nt(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`||tt.test(i.name))&&i.startTime>=n){let e=et(i.name);e&&(t=e,n=i.startTime)}return t}function B(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var rt=class{video;baseFrames=0;baseDropped=0;lastFrames=0;lastDropped=0;constructor(e){this.video=e}read(){let e=B(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 it(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 at=2e3,ot=3,V=500,st=6e3,ct=.25,lt=250,ut=.05,dt=4;function ft(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 H(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function U(){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 pt(){if(typeof navigator>`u`||!U())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var W=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;fairplayKeyIV;loadStarted;preloadTouched=!1;savedPreload=null;cdnHost=``;builtAt;frameCounter;detachFrames=null;constructor(e){this.deps=e,this.frameCounter=new rt(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.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=ht(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)=>a({type:`error`,error:new l(d(t),t,e),fatal:n});this.onEncrypted=a=>{let c=a;c.initData&&!this.fairplayArmed&&(this.fairplayArmed=!0,this.fairplayKeyIV=ft(c.initData),(async()=>{try{let a=await(await navigator.requestMediaKeySystemAccess(`com.apple.fps`,[{initDataTypes:[c.initDataType],videoCapabilities:[{contentType:`application/vnd.apple.mpegurl`,robustness:``}],distinctiveIdentifier:`not-allowed`,persistentState:`not-allowed`,sessionTypes:[`temporary`]}])).createMediaKeys(),l=await fetch(o.certificateUrl,{headers:{"x-api-key":n.apiKey}});if(!l.ok){this.fairplayArmed=!1,s(`FairPlay certificate request failed: ${l.status}`,l.status,!0);return}await a.setServerCertificate(await l.arrayBuffer()),await e.setMediaKeys(a);let u=a.createSession();this.keySession=u,u.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){s(`FairPlay license request failed: ${a.status}`,a.status,!0);return}await u.update(new Uint8Array(await a.arrayBuffer()))}catch(e){s(`FairPlay license request failed: ${String(e)}`,0,!0)}})()}),await u.generateRequest(c.initDataType,c.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||=nt(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<=dt,!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=G();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=at&&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=G,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=V;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+ct),s=Math.max(r,t()-n)>=st;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,V)};this.refocusTimer=setTimeout(i,V)}cancelRefocus(){this.refocusTimer!=null&&clearTimeout(this.refocusTimer),this.refocusTimer=null}watchBufferedEnd(){if(this.edgeTimer!=null)return;let{video:e}=this.deps;this.onEdgeReset=()=>{this.lastBufferedEnd=null,this.bufferedAdvancedAt=null},e.addEventListener(`seeking`,this.onEdgeReset),e.addEventListener(`emptied`,this.onEdgeReset),this.edgeTimer=setInterval(()=>{if(e.duration!==1/0)return;let t=mt(e,e.currentTime);t!=null&&((this.lastBufferedEnd==null||Math.abs(t-this.lastBufferedEnd)>=ut)&&(this.bufferedAdvancedAt=G()),this.lastBufferedEnd=t)},lt)}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.lastBufferedEnd=null,this.bufferedAdvancedAt=null}liveEdgeEstimate(){let e=this.deps.video;if(e.duration!==1/0)return null;let t=this.liveEnd(),n=mt(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,(G()-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-ot,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 G(){return typeof performance<`u`?performance.now():Date.now()}function mt(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 ht(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function K(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 gt=15e3,_t=5e3,vt=6;function yt(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var bt=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=yt(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;if(i>=vt)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)},gt)}take(e){let t=yt(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 xt(e){let t=c.default.DefaultConfig?.loader;if(typeof t!=`function`)return;class n extends t{served=!1;cancelled=!1;stats=St();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||_t,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 St(){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 q(e){return e===`audio`?`audio`:`main`}function Ct(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 wt(){return c.default.isSupported()}var Tt=3,Et=5,Dt=3,Ot=1e4,kt=3e4,At=12e3,jt=3e3,Mt=.02,Nt=6e3,Pt=.5,Ft=3,It=.5,Lt=1.1,Rt=.25,zt=5e3,Bt=4e3,Vt=2,Ht=5,Ut=2,Wt=2,Gt=4,Kt=4,qt=2e3,Jt=3e4,Yt=.2,Xt=30,Zt=2,Qt=2,$t=9,en=.5,tn=64;function nn(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Qt;let t=Math.max(12,e.liveSyncDuration+$t);(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 an=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;recentMainFrags=[];chaseSuspended=!1;savedLiveMaxLatency;savedMaxSyncRate;chaseLatency=-1;catchUpRate=1;catchUpEngaged=!1;onTimeUpdate=null;chaseTicks=0;liveRetargets=0;capObserver=null;capTimer=null;sizeCapLevel=null;bitrateCapLevel=-1;fpsCapBitrate=null;fpsCapFailedHeight=null;fpsCapManaged=!0;fpsLastFrames=-1;fpsLastDropped=-1;fpsBadTicks=0;fpsDownCaps=0;sizeCapManaged=!0;dprMedia=null;onDprChange=null;loadStarted;frameCounter;detachFrames=null;constructor(e){this.deps=e,this.frameCounter=new rt(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=H(n)&&U(),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&&(Ie(n),Be()),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}},zt))}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+en||(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)<Mt)){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=H(this.deps.video)&&U(),f={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,liveDurationInfinity:!0,maxBufferHole:.5,maxLiveSyncPlaybackRate:d?1:1.1,abrEwmaDefaultEstimate:1e6,capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...u?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:I.video,audioRobustness:I.audio,videoEncryptionScheme:I.scheme,audioEncryptionScheme:I.scheme},...N()?{requestMediaKeySystemAccessFunc:Fe(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||!K(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),Ot)});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 bt({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=xt(e);n&&(this.prefetch=e,f.fLoader=n)}nn(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,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},kt)))}),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);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>tn&&this.requestTimesMs.shift());let a=t?.frag?.url;if(a){let e=et(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=q(r?.type);if(r&&e.isActive(i))for(let t of Ct(p,r))e.prefetch(t.url,i,t.kind)}),p.on(c.default.Events.KEY_LOADED,(t,n)=>e.keyUsable(q(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.checkFrameDrops()},jt),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,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=1;return!a.ignoreDevicePixelRatio&&typeof self<`u`&&self.devicePixelRatio>0&&(o=self.devicePixelRatio),o=Math.min(o,a.maxDevicePixelRatio??1/0),c.CapLevelController.getMaxLevelByMediaSize(e.levels,r*o,i*o)}onMediaResize(){if(!this.sizeCapManaged)return;let e=this.computeSizeCapTarget();if(e==null)return;if(this.sizeCapLevel==null){this.applySizeCap();return}if(e===this.sizeCapLevel){this.capTimer&&=(clearTimeout(this.capTimer),null);return}this.capTimer&&clearTimeout(this.capTimer);let t=e>this.sizeCapLevel?qt:Jt;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=>Ve(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&L(e)!==`avc`&&!!L(e)));for(let n of t)ze(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&&L(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:!L(e.videoCodec)||Ve(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=[this.sizeCapLevel??-1,this.bitrateCapLevel,this.fpsCapLevel(e)].filter(e=>e>=0);e.autoLevelCapping=t.length?Math.min(...t):-1}getAudioTracks(){return this.hls?this.hls.audioTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0,default:!!e.default})):[]}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}getTextTracks(){return this.hls?this.hls.subtitleTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0})):[]}setTextTrack(e){let t=this.hls;t&&(e<0?(t.subtitleTrack=-1,t.subtitleDisplay=!1):(t.subtitleTrack=e,t.subtitleDisplay=!0))}seekToLive(){let e=this.hls;e&&typeof e.liveSyncPosition==`number`&&(this.deps.video.currentTime=e.liveSyncPosition)}setLicenseUrls(e){e.widevine&&(this.licenseUrl=e.widevine)}getStats(){let e=this.hls,t=this.frameCounter.read(),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames,lowLatency:this.detectedLowLatency,bytesLoaded:this.bytesLoaded,playlistBytesLoaded:this.playlistBytesLoaded,renditionSwitches:this.renditionSwitches,liveRetargets:this.liveRetargets,fpsDownCaps:this.fpsDownCaps,licenseTimeMs:this.licenseTimeMs,upshifts:this.upshifts,downshifts:this.downshifts,requestCount:this.requestCount,requestErrors:this.requestErrors,requestTimesMs:[...this.requestTimesMs],ladderHeights:this.ladderHeights,ladderTopBitrateKbps:this.ladderTopBitrateKbps||void 0};if(this.cdnHost&&(n.cdnHost=this.cdnHost),this.licenseRequested&&(n.keySystem=`widevine`,n.drmSecurityLevel=`L3`),e){n.qualityPinned=!e.autoLevelEnabled,typeof e.latency==`number`&&(n.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(n.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(n.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let t=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;t&&(n.levelHeight=t.height),t?.videoCodec&&(n.videoCodec=t.videoCodec),t?.audioCodec&&(n.audioCodec=t.audioCodec),t&&typeof t.bitrate==`number`&&(n.renditionBitrateKbps=Math.round(t.bitrate/1e3)),typeof t?.details?.live==`boolean`&&(n.isLive=t.details.live,typeof e.liveSyncPosition==`number`&&(n.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return n}trackEnd(e){let t=e.details;if(t){if(t.live===!0){this.sawLive=!0;let e=t.endSN??-1;e!==this.lastEndSN&&(this.lastEndSN=e,this.lastAdvanceMs=Date.now(),this.chaseSuspended&&this.resumeChasing());return}this.sawLive&&this.emitEnded(`endlist`)}}checkEndStale(){if(this.endedEmitted||!this.sawLive||this.lastAdvanceMs===0)return;if(typeof document<`u`&&document.hidden){this.lastAdvanceMs=Date.now();return}if(this.loadSuspended){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>Nt&&this.suspendChasing(),e>At&&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<Nt,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>Bt,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=B(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>Gt&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=Ut&&(this.clearKick(),this.starvationRebuilds<Wt)){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>=Vt,d=!i&&this.deadTicks>=Gt&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=Kt;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=Ht))){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>Pt?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=Pt&&this.deps.video.playbackRate===1&&(this.catchUpEngaged=!1);let i=this.catchUpEngaged?this.catchUpRate:1;e.config.maxLiveSyncPlaybackRate!==i&&(e.config.maxLiveSyncPlaybackRate=i)}fpsCapLevel(e){if(this.fpsCapBitrate==null)return-1;let t=this.fpsCapFailedHeight,n=-1;return e.levels.forEach((e,r)=>{let i=t==null||!(e.height>0)||e.height<t;e.bitrate<=this.fpsCapBitrate&&i&&(n=r)}),n<0?0:n}resetFrameDropWindow(){this.fpsLastFrames=-1,this.fpsLastDropped=-1,this.fpsBadTicks=0}checkFrameDrops(){let e=this.hls,{video:t}=this.deps;if(!e||!this.fpsCapManaged||this.loadSuspended||t.paused||!e.autoLevelEnabled||typeof document<`u`&&document.hidden){this.resetFrameDropWindow();return}let{totalFrames:n,dropped:r}=B(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<Xt||o<0){this.fpsBadTicks=0;return}if(o<=Yt*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<Zt)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(Lt,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=It){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<Ft)return;this.resetChaseWindow();let a=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;if(!(a>1))return;let o=typeof e.targetLatency==`number`?e.targetLatency:0,s=Math.min(n,a-1);s<o+Rt||(console.warn(`havik-player: catch-up at ${r}x not gaining on the live edge (latency ${n.toFixed(1)}s); holding at ${s.toFixed(1)}s`),this.liveRetargets+=1,e.targetLatency=s)}suspendChasing(){let e=this.hls;if(!e)return;this.chaseSuspended=!0,this.savedLiveMaxLatency=e.config.liveMaxLatencyDuration,this.savedMaxSyncRate=e.config.maxLiveSyncPlaybackRate,e.config.liveMaxLatencyDuration=2**53-1,e.config.maxLiveSyncPlaybackRate=1;let{video:t}=this.deps,n=this.savedMaxSyncRate;t.playbackRate>1&&typeof n==`number`&&t.playbackRate<=n&&(t.playbackRate=1)}resumeChasing(){this.chaseSuspended=!1;let e=this.hls;e&&(e.config.liveMaxLatencyDuration=this.savedLiveMaxLatency,e.config.maxLiveSyncPlaybackRate=this.savedMaxSyncRate)}emitEnded(e){this.endedEmitted||(this.endedEmitted=!0,this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.deps.emit({type:`ended`,reason:e}))}stop(){this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.clearKick(),this.stopped=!0,this.loadSuspended=!1,this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null);try{this.hls?.stopLoad()}catch{}try{this.deps.video.pause()}catch{}}destroy(){if(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>=Dt)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{this.licenseRetryTimer=null,this.rebuildInstance(`license retry`)},n),!0}rebuildInstance(e){if(this.hls){try{this.hls.destroy()}catch(t){console.warn(`havik-player: hls.js destroy() threw during ${e}`,t)}this.hls=null,this.startHls()}}onError(e){if(e.type===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<Et){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<Tt){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??``;return new l(t===`DRM`?d(n):n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`)}},on=15e3,sn=6e5,cn=3e5,ln=100,J=1,un=1e3,dn=3e4,fn=1e3,pn={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},mn={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`};function hn(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}var gn=new Set([`INVALID_URN`,`NOT_FOUND`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),Y={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 _n(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 vn=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),yn=new Set,X=new Set,Z=new Set,bn=e=>`this page's Content-Security-Policy blocks QoE beacons. Add ${e} to connect-src; until then none are sent.`;function xn(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(yn.has(t)&&!X.has(t)){X.add(t),b(bn(new URL(t).origin));for(let e of Z)e.noteCspBlocked()}}function Sn(e,t){return b(t,e),{disabledReason:t}}function Cn(e,t,n){if(n)return t&&!vn(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return Sn(`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=_n(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return Sn(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 wn=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??on,idleMs:e.idleMs??sn},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(),un),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&&yn.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,xn),Z.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,cn);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(J,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(J,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(J,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:Y[e]??`PLAYER_STATE_UNSPECIFIED`,toState:Y[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:pn[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<fn}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(J,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=J),this.firstPlaylistMs>0&&(this.firstPlaylistMs=J),this.firstFragLoadMs>0&&(this.firstFragLoadMs=J),this.drmSetupMs>0&&(this.drmSetupMs=J))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(J,this.now()-this.startupAnchorMs))}noteFirstPlaylist(){this.firstPlaylistMs===0&&(this.firstPlaylistMs=Math.max(J,this.now()-this.startupAnchorMs))}noteDrmReady(){this.drmSetupMs===0&&(this.drmSetupMs=Math.max(J,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(J,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`)return`ERROR_STAGE_DRM`;if(gn.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=Y[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=hn(n,50),o.requestTimeP95Ms=hn(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=mn[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,Z.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<=dn&&(i.abandonAfterStallMs=Math.max(J,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=dn&&(i.abandonAfterErrorMs=Math.max(J,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?.(bn(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&X.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>ln;){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 Tn(){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 En(){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 Dn(){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 On(e){let t=Tn(),n={deviceClass:En(),integration:t.integration,...Dn()};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 kn(){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 An=`2.16.12`,jn={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`},Mn={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 Nn(e,t){let n={...jn,...t};for(let t of Object.keys(Mn))e.style.setProperty(Mn[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var Pn=`havik-player-styles`,Fn=`
|
|
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}
|