Skip to content

Havik Player SDK API Reference ​

@oddin-gg/havik-player · HTML5 player SDK for Oddin live streams (LL‑HLS + DRM).

This is the complete API reference. For a quick start, see the README.


Contents ​


Overview ​

The SDK plays Oddin live streams in the browser over Low‑Latency HLS with DRM, and offers three integration modes:

ModeEntry pointYou provideThe SDK handles
A (managed)createPlayer()a <video> elementhls.js, LL‑HLS, DRM/EME, retries, stats
B (bring your own player)resolveStream()your player + <video>auth → catalog → playback resolution + DRM helpers
C (iframe embed)mountEmbed()an iframe sloteverything, behind a postMessage API

All modes are exported from the package root and are fully typed (TypeScript definitions ship in the package).


Installation ​

npm / bundlers:

bash
npm install @oddin-gg/havik-player
ts
import { createPlayer, resolveStream, mountEmbed } from '@oddin-gg/havik-player';

Via <script> (CDN): exposes a global window.HavikPlayer.

html
<script src="https://cdn.jsdelivr.net/npm/@oddin-gg/havik-player/dist/havik-player.global.js"></script>
<script>
  const player = await HavikPlayer.createPlayer({ /* … */ });
</script>

In production, pin a version in the CDN URL: …/havik-player@X.Y.Z/dist/….

The package is ESM, side‑effect‑free, and ships ES2022 output plus a self‑contained IIFE bundle for <script>/iframe use.


Concepts ​

What you need ​

Two values are required to play any stream:

  • A match URN: identifies the event, e.g. od:match:1234.
  • A publishable api‑key: e.g. pk_live_… (production) or pk_test_… (test). The key must be configured with an allowed origin list that includes the origin your player runs on. See Onboarding & CORS.

You also need the API base URL: https://feed-dev.oddin-video.gg for the integration environment, https://feed.oddin-video.gg for production. Treat the endpoint directory as the source of truth rather than hard-coding either. See Service URL discovery.

Credentials ​

Every API call carries your api‑key. Pass it as a Credential, or as a function returning one; see CredentialSource. The function form is called per request, so it supports transparent refresh if you later move to short‑lived tokens.

ts
// static
const credential = { apiKey: 'pk_live_…' };

// dynamic (called per request)
const credential = async () => ({ apiKey: await myTokenService.get() });

The play sequence ​

  1. (Optional) Discover live/upcoming matches with fetchCatalog(), or watch a single match's status with watchStatus().
  2. Resolve playback: resolveStream() returns a StreamDescriptor with the manifest URL and DRM config.
  3. Play: feed the descriptor to the managed player (Mode A) or your own player (Mode B).
  4. DRM licenses are acquired automatically by the player's EME layer as the CDM encounters encrypted media.

Match status is available as a push channel (subscribeLiveState, SSE), used automatically by the managed player, with polling (watchStatus / waitForLive) as the fallback. The authoritative signal that a stream is playable is still a successful playback resolution (not catalog status, which can briefly lead the stream going live).

Live pickup ​

A match scheduled to go live isn't immediately playable. The waitForLive option arms the player and attaches the instant the stream goes live, with zero manual action. By default it does this over the push channel (SSE, subscribeLiveState): while connected it makes no /v1/playback requests, waits for the pushed live, then resolves once. If the SSE endpoint is unavailable it falls back to polling TOO_EARLY + the server's Retry-After. End-of-stream is detected automatically too: the player stops and fires ended. And ended is not necessarily forever: if the encoder reconnects after an outage long enough to tear the session down, the recreated session serves under a new manifest URL: so on the next pushed live the player rejoins automatically (re-resolves and re-attaches, rejoinOnLive option). Set liveStateEvents: false to force polling-only.

See WaitForLive for tuning, and createPlayer / resolveStream for usage.

DRM ​

  • Key systems: Widevine (com.widevine.alpha) and FairPlay (com.apple.fps). PlayReady is not used (Windows/Edge play via Widevine).
  • Container/encryption: CMAF/fMP4, cbcs.
  • The playback descriptor's drm.*.licenseUrl values are pre‑signed. When you integrate your own player (Mode B), you must POST to the license URL verbatim: its signed query string is the access token; do not rewrite, re‑encode, or strip parameters. Use the same api‑key to resolve playback and to fetch licenses. The managed and iframe players handle this for you.

FairPlay (Safari/iOS): played by the browser's native player. When the playback descriptor carries FairPlay material and the browser is WebKit, engine: 'auto' selects the native engine, which fetches the application certificate, handles the encrypted event, POSTs the SPC to the signed license URL and applies the returned CKC. hls.js is not used for FairPlay: through MSE, WebKit reports the key usable and still renders nothing. No configuration is needed beyond the same api‑key used for playback.

iOS third‑party browsers (Chrome/Firefox/Edge on iOS): iOS has no Widevine CDM, so protected playback in these browsers depends entirely on whether the WebKit build grants them FairPlay. Don't assume either way: call detectDrmSupport and let the probe decide, so viewers see an accurate message instead of a black player.

Browser support ​

BrowserEngineDRM
Chrome, Edge (desktop & Android)hls.jsWidevine ✓
Firefoxhls.jsWidevine ✓
Safari (macOS)hls.js; native for FairPlayFairPlay ✓ (native engine)
Safari (iPhone, iPad)native HLSFairPlay ✓ (native engine)
Chrome/Firefox/Edge on iOSnative HLSprobe with detectDrmSupport (no Widevine on iOS)

Requires a browser with Media Source Extensions and Encrypted Media Extensions (all evergreen browsers), or native HLS (iPhone, iPad, and older Safari).


Mode A: Managed player ​

The SDK owns the <video> element, bundles hls.js, and wires LL‑HLS + DRM automatically. It also handles live‑pickup retries, buffering recovery, stats, and silent DRM license refresh for long sessions.

createPlayer ​

ts
function createPlayer(opts: CreatePlayerOptions): Promise<Player>;

Resolves to a Player as soon as the stream is attached (or armed, when waitForLive is set and the match is still upcoming). Terminal errors during the initial resolution (e.g. NOT_FOUND, GEO_DENIED, GONE, UNAUTHORIZED) reject the promise; the live wait itself never blocks the promise and is surfaced through 'waiting' events.

ts
const player = await createPlayer({
  video: document.querySelector('video')!,
  env: 'integration', // or 'production' — see baseUrlForEnv for Modes B/C
  matchUrn: 'od:match:1234',
  credential: { apiKey: 'pk_test_…' },
  autoplay: true,
  muted: true,
  waitForLive: true,
});

player.on('statechange', (state) => console.log(state));
player.on('waiting', (w) => console.log(`live in ~${Math.round(w.retryInMs / 1000)}s`));
player.on('stats', (s) => console.log(s.droppedFrames, s.latencySeconds));
player.on('error', (e) => console.error(e.code, e.httpStatus, e.message));

CreatePlayerOptions ​

OptionTypeDefaultDescription
videoHTMLVideoElement—Required. The element the SDK will control.
env'integration' | 'production'—Required unless baseUrl is given. Which Oddin environment to play against. Preferred: the host is correct by construction, and so is everything derived from it (the SSE events host, the QoE beacons host).
baseUrlstring—Required unless env is given. API base URL, e.g. https://feed-dev.oddin-video.gg. Use for a deployment the named environments do not cover: your own CDN or gateway fronting the streams API, the CN plane, or a pinned build that must outlive a domain change. Passing both env and baseUrl — or neither — is a compile error in TypeScript and throws at runtime in JavaScript.
matchUrnstring—Required. The match to play, e.g. od:match:1234.
credentialCredentialSource—Required. Your api‑key (or a function returning one).
autoplaybooleantrueStart playback once ready. With false, the player holds in a pre-play 'paused' state (poster + play card, no spinner) and fetches no media and no DRM license until the first play(). On the hls.js engine the manifest is still parsed pre-play, so 'ready' and the track lists keep working; the native (Safari) engine defers all fetching and emits 'ready' at attach instead. Note: if a programmatic play() is policy-blocked (autoplayblocked), the loader keeps warming the buffer — media and DRM traffic flows from that kick, not from a viewer gesture.
mutedbooleanfalseMute the element. Set true for reliable autoplay under browser sound policies.
controls'custom' | 'native' | 'none''custom'Which controls to render. See Controls & theming.
themePartial<HavikTheme>Oddin brandRe-skin the custom control bar (ignored unless controls: 'custom'). See Controls & theming.
statusOverlaysbooleantrueBranded full-bleed cards for the stopped/pre-play states (ended, fatal error, pre-play, armed-waiting) instead of a frozen frame + a dead play button. Themed via the control-bar tokens + theme.logoUrl. Set false to render your own UI from the ended/error events. Ignored unless controls: 'custom'.
cspNoncestring—Your page's CSP nonce, stamped on the <style> tag the custom control bar injects. Needed only when style-src has no 'unsafe-inline': without it the browser blocks the tag and the controls render unstyled. See Content-Security-Policy. Ignored unless controls: 'custom'.
endedMessagestring"This stream has ended"Message on the end-of-stream card.
interruptedMessagestring"Reconnecting — please stand by"Message shown instead of endedMessage when the server reports the stream stopped but the match is still running (endedReason: 'interrupted', an ingest outage that outlived the bridge's hold). The player rejoins automatically when the stream returns while rejoinOnLive is on (the default); override this wording if you disable auto-rejoin, since nothing will re-attach on its own.
errorMessagestringthe error's messageMessage on the fatal-error card (otherwise the error's own message).
offlineMessagestring"No internet connection — waiting to reconnect"Message on the card shown while the browser reports no network (navigator.onLine === false). It replaces the error and reconnecting cards for as long as the browser says offline and carries no Retry button: nothing can succeed without a route, and the player resumes by itself on the browser's online event. See Connectivity.
waitForLiveWaitForLive—Arm on an upcoming match and auto‑attach at go‑live.
lowLatency'auto' | boolean'auto''auto' lets the player decide from the manifest.
engine'auto' | 'hls' | 'native''auto''auto' uses the browser's native player on iPhone and iPad for every stream, and for FairPlay on any Apple browser; elsewhere it prefers hls.js (desktop Safari included) and falls back to native HLS. hls.js on iOS runs on ManagedMediaSource, which closed mid‑session and played slower than real time in testing.
userIdstring—Optional viewer id (sent as X-User-Id on license requests).
debugbooleanfalseTurn on hls.js's internal console logging: fragment/part scheduling, ABR switches, EME key sessions and license traffic. For diagnosing a playback problem with Oddin support; leave it off in production (it logs on every fragment, and the EME lines include license request/response metadata). hls.js engine only. hlsConfig.debug still wins if you set both.
hlsConfigPartial<HlsConfig>—Escape hatch for advanced hls.js tuning.
statsIntervalMsnumber2000How often 'stats' is emitted.
licenseRefreshMsnumber480000 (8 min)How often to silently re-resolve playback so the signed DRM license URL the player would use next stays inside its signature lifetime (~10 min). Refreshes the URL, not the license: it cannot extend a license the CDM already holds, so a session that outlasts its license still ends with a fatal DRM_CLIENT error. 0 disables the timer only: a lapsed URL is still refreshed on refocus and before a license request (Widevine on hls.js; the native FairPlay engine has neither check).
posterstring—Poster image shown before playback starts.
startLevelnumber-1Initial rendition index (-1 = auto). With auto, ABR starts on a conservative, sustainable rendition (~360p) and ramps up as bandwidth allows; see Low‑latency & adaptive bitrate.
maxBitratenumber—Cap ABR to renditions at/below this bitrate (bps).
liveLatencyTargetnumber2Target live‑edge latency in seconds (hls.js liveSyncDuration). The player derives a matching latency ceiling internally and catches up at 1.1×, so this is the only live‑latency knob you need. Lower = closer to live but more rebuffer‑prone. Live/LL only.
adaptiveHoldBackbooleantruehls.js engine: raise the live‑sync target for a session whose part fetches are slow, instead of letting it stall. A viewer far from the origin plays from a local edge whose every cache miss on a 0.5 s part is a cross‑continent fetch (250–310 ms per part from South America, Canada/Mexico and APAC on the global slot, against 44 ms in Europe), so the fetch cycle outruns the part cadence and the 2 s buffer drains. The session's own part fetches are timed (first byte, as a share of the part's duration, over a 10 s window): a window whose p95 is at or above 60% and whose median is at or above 40%, two 3 s ticks running, steps the target up 0.5 s, to adaptiveHoldBackCeiling at most; a p95 under 40% for 60 s steps it back down. A session whose fetches are fast never moves. Each move fires latencytargetchange, counts in holdBackSteps, and shows in targetLatencySeconds. Live/LL only.
adaptiveHoldBackCeilingnumber3.5Highest live‑sync target the adaptive hold‑back may step to, in seconds. Kept a second under the drift ceiling; at or below liveLatencyTarget it disables the stepping.
stallCapbooleantruehls.js engine: after a playback stall (not in the first 10 s after playback starts or resumes, not while seeking, not with media still buffered ahead, not a wait at the live edge for a part not yet published), cap quality one rendition below the one that stalled, and give one rendition back per 3 minutes of playback without another stall (paused time does not count); a stall while capped steps down again or restarts the 3 minutes. Without it, ABR climbs straight back onto a rendition the connection just failed to carry: on measured production sessions, 55–65 % of rebuffer time was such a repeat within 3 minutes. Counted in stallDownCaps; capReason is 'stall' while it is the binding ceiling. Never applies to a quality the viewer pinned; off when hlsConfig.capLevelToPlayerSize or capLevelOnFPSDrop: true hands capping to hls.js.
snapToLiveOnRefocusbooleantrueSnap to the live edge when a backgrounded tab is refocused: on hls.js while far behind; on the native player (iPhone, iPad, FairPlay) on every return after 2 s or more away and on every back/forward‑cache restore, 3 s behind the edge once the first playlist refresh after the return moves it (up to 6 s wait; the edge on return is still the one from before leaving), which also redraws a picture iOS left black. Live/LL only.
stuckReloadbooleantrueNative engine (Safari, iPhone, iPad), live only: when the playhead has not moved and the buffered media under it has not grown for 8 s, with the page visible, the element playing and the browser online, the player reloads the stream at the live edge. WebKit's native HLS has a freeze it never leaves by itself: on production iPhone Safari over 8 days to 2026-11-04 there were 2.31 such freezes per watch-hour (hls.js on Android, on the same CDN slots and in the same countries: 0.35), not one recovered on its own, and viewers paused or left after a median 24 s. At most twice per 30 s of healthy playback; a slow start, a seek, a pause, a hidden tab and an offline browser never count. Each reload counts in stuckReloads.
rememberBandwidthbooleantruehls.js engine: start from the bandwidth this device measured in a recent session (localStorage key havik.player.bandwidth, per connection type, up to 3 days old, reused at 80%) instead of the conservative ~1 Mbps start; a slow record starts from that lower figure (0.3 Mbps floor). A first visit, a stale record or blocked storage keeps the conservative start; an explicit hlsConfig.abrEwmaDefaultEstimate or startLevel wins. Reset with clearRememberedBandwidth().
sizeCapHeadroomnumberunsethls.js engine: rendition rungs ABR may pick above the one that merely covers the player's pixel box. Unset: 1 on displays below 2× devicePixelRatio, earned per session on LL-HLS (its parts download within half a part duration even at that rung's bitrate, the bandwidth estimate is twice the rung and stays above 1.5×, and no stall in the last 2 minutes; a stall after the first 10 s of playback drops the rung at once; streams without parts get the rung as before), 0 at 2× and above. A 960 px box at 1x covers with 960×540; one rung of headroom plays 720p downscaled instead, which looks sharper for the same box; phones and 2× screens keep the cover-only cap (their covering rung already matches their device pixels; a rung above it mostly costs data). An explicit value applies on every display: 0 = strict cover-only cap, Infinity = no size cap. Never past the top rung; maxBitrate and the frame-drop cap still apply. hlsConfig.capLevelToPlayerSize: true caps to the covering rung with no headroom.
mediaDuringKeybooleantrueDRM cold start: download the first init segment and parts while the first key is still being acquired, instead of after it. Bytes reach hls.js only when it asks for them; only the network time moves off the critical path (~0.5 s on Widevine LL-HLS). Ignored on clear streams and when hlsConfig.fLoader is set. Pass false to opt out.
preloadHintsbooleantrueLive LL-HLS, hls.js engine: fetch the part each playlist's EXT-X-PRELOAD-HINT names as soon as the playlist arrives, instead of after the next playlist lists it. The origin and CDNs hold that request until the part exists, so a viewer far from the origin saves about one round trip per part (measured from São Paulo: late parts at a 3 s live distance went from 100 % to 0 %). Bytes reach hls.js only when it asks for the part; an unrequested hint is dropped after 4 s or on a rendition switch. Off while paused and while loading behind the live edge. Ignored when hlsConfig.fLoader is set. Pass false to opt out.
liveStateEventsbooleantrueUse the push-based live-state SSE channel for go-live and end-of-stream (see Live state). Graceful: falls back to polling if the endpoint is unreachable; a 410 (match gone) stops the subscription and a 404 (not in the catalog) slows it to one retry every 5 min, each with one warning. On a return from the background (5 s or more away, or a back/forward-cache restore) the subscription is reopened so the server replays the current state: a page suspended through the end of a match does not sit buffering on a socket that will never deliver it. Set false to disable.
rejoinOnLivebooleantrueRejoin automatically when a stream that ended comes back live. An ingest outage longer than the bridge's reconnect grace recreates the session under a new manifest URL (the old playlist freezes at HTTP 200), so the player keeps the live-state subscription open after ended (until gone) and re-arms on a pushed live. Set false to keep ended terminal. Needs liveStateEvents.
analyticsboolean | { endpoint?: string }trueQoE beacons. Active only when the playback response carries a server-minted sid. havik-streams v0.10.0+ names the beacons host in that response, and it is used whatever baseUrl is; it also wins over { endpoint } (a differing value is ignored with one console.warn). Against an older server the host is { endpoint } if given, else derived from baseUrl by hostname convention (feed[-dev].<domain> → beacons[-dev].<domain>); there, if baseUrl is not a feed host nothing derives and beacons are disabled — the SDK then logs one console.warn naming the host and emits a non-fatal warning event carrying the same sentence. Recovery: pass { endpoint: 'https://beacons[-dev].<domain>' }. Pass false to opt out deliberately (no warning).
eventsBaseUrlstringderivedOverride the SSE endpoint base. Default: baseUrl with the host prefixed by events. (e.g. feed.<d> → events.<d>).

Low-latency & adaptive bitrate ​

The player ships tuned defaults for Oddin's low‑latency HLS, so you normally don't need to set any of the live or ABR knobs:

  • Live latency: playback targets ~2 s behind the live edge (liveLatencyTarget → hls.js liveSyncDuration). It deliberately sits back from the bleeding PART‑HOLD‑BACK edge, where the newest partial segments aren't reliably published yet; chasing that edge causes constant rebuffering. Set liveLatencyTarget lower for closer‑to‑live (more rebuffer‑prone) or higher for steadier playback. Lowered from 3 s; see the migration note below.
  • Catch‑up dead band: the player only speeds up when it is more than 0.5 s behind its target. Smaller gaps, like the 0.1 to 0.4 s a viewer typically lands behind on joining, are left alone, because even 1.05× is audible as a crackle in Chrome's and Firefox's pitch correction. Once catch‑up starts it runs until playback is back on target.
  • Drift ceiling: after a stall, the player catches up at up to 1.1× (gentle enough to be invisible; it was 1.5×, which showed as the picture speeding up between stalls on a jittery edge) and, as a backstop, force‑seeks back toward the target once latency exceeds an internal ceiling (~12 s, derived as max(12, liveLatencyTarget + 9)). This is what stops latency from snowballing to tens of seconds after buffering. The ceiling is internal and always kept above your liveLatencyTarget.
  • No catch‑up rate on Safari. On a WebKit media stack the catch‑up rate is 1.0×: every playback‑rate change froze Safari's picture for 270–480 ms with media buffered (measured 2026‑10‑18), which outweighs the drift it recovers. Drift there is corrected by the ceiling's seek alone; hlsConfig.maxLiveSyncPlaybackRate puts a rate back if you want it.
  • Over‑seek clamp: the drift ceiling's counterpart on the near side. A seek that lands closer to live than liveLatencyTarget is pulled back onto it, so dragging the scrub bar to its far right means "go live" rather than landing on the bleeding edge, where latency reads under a second and playback stutters frame‑by‑frame on an empty forward buffer. hls.js can't recover from that state on its own (its live‑sync only ever corrects being behind), so the stutter would otherwise persist for the rest of the session. Live only: VOD seeks are untouched, and the clamp stands down while chasing is suspended on a stale playlist (there is no live edge left to protect at that point). The custom control bar hides its seek bar on a live stream (the Go‑live button and seekToLive() are the way back to the edge); on VOD the bar covers the full duration. Bring‑your‑own‑player (Mode B) owns its own seek UI and needs the equivalent clamp itself.
  • Small‑gap tolerance: maxBufferHole is hls.js's default (0.1 s). Earlier releases raised it to 0.5 s as headroom; the streams sampled since have no audio gaps at segment or part boundaries, and the larger value only changed which skipped tail parts were merged over and which were re-fetched. Set it through hlsConfig if a stream needs it.
  • Start quality: auto ABR seeds a ~1 Mbps estimate so the first rendition is one a modest link can sustain (~360p) and then ramps up within a few seconds as measured bandwidth allows, rather than grabbing a high rung and rebuffering on a constrained link. This trades a slightly softer first ~2 s for a stall‑free start (the first‑seconds buffering fix). A device that has measured a fast line in the last 3 days starts from that measurement instead (rememberBandwidth, on by default: the estimate after ~10 s of playback, stored per connection type and reused at 80%), so a returning viewer on a fast line starts near full quality without a 360p jump, and a device that measured a slow line starts from that lower figure (also at 80%, never below 0.3 Mbps). A first visit or a device with no usable record keeps the ~1 Mbps start. In addition, the session is bounded to the player's pixel box plus one rung of headroom, once the session shows it can carry it, on displays below 2× devicePixelRatio (sizeCapHeadroom; set it explicitly to apply a value on every display), so a small/embedded player won't fetch 1080p, while a 960 px desktop embed gets 720p downscaled rather than 540p at 1:1 (a lower encode shown pixel‑for‑pixel looks softer than a higher one scaled down; measured on production, Windows viewers sat at ≤540p 73% of the time with bandwidth to spare). Phones and 2× screens keep the cover‑only cap. The cap is SDK‑managed and debounced rather than hls.js's own capLevelToPlayerSize poller: a size change only reaches ABR once the box has been stable for ~2 s (raise), and a shrink is applied lazily (~30 s), so a fullscreen enter/exit never forces a quality switch, and its ~1 s stall, mid‑transition (the higher rendition simply downscales into the smaller box until the down‑cap lands). Passing hlsConfig.capLevelToPlayerSize: true restores hls.js's immediate poller and stands the SDK manager down, including the headroom: the poller caps to the covering rung only. The ceiling in force and which limit set it are reported in every stats event (maxLevelHeight, capReason), so a player stuck at 540p in a 758 px box can say so. Pin a fixed rung with startLevel, cap the top with maxBitrate, or raise the seed via hlsConfig.abrEwmaDefaultEstimate if you want a sharper (higher‑risk) start.

All of these can be overridden through hlsConfig (e.g. maxLiveSyncPlaybackRate), but the defaults are tuned for Oddin's streams and rarely need changing. Raw live‑sync overrides are normalized so they can't crash the player: if you pass the count‑based liveSyncDurationCount / liveMaxLatencyDurationCount, the seconds‑based defaults step aside (hls.js rejects mixing the two); if you set liveSyncDuration alone, a matching ceiling is derived above it.

  • Quality steps down after a stall, and comes back slowly. A playback stall (not in the first 10 s after playback starts or resumes, not during a seek, not with media still buffered ahead, not a wait at the live edge for a part not yet published) caps ABR one rendition below the one that stalled; each further 3 minutes of playback without a stall gives one rendition back. ABR otherwise climbs straight back to the rendition that just failed, which on slow connections is most of the rebuffering. Counted in stallDownCaps; stallCap: false turns it off.

  • Quality steps down when the device can't decode it. If the browser keeps dropping more than 20% of frames for two 3 s checks in a row, the SDK caps ABR one rendition below the one playing (counted in fpsDownCaps). The two checks right after a quality switch are not counted: the decoder restarts on the new rendition and drops frames for a few seconds on its own. This is what keeps a laptop without hardware decoding from showing a stuttering picture that drifts away from the sound. It folds into the same cap as the player‑size and maxBitrate limits, never applies to a quality the viewer pinned, and stays down for the session. Setting hlsConfig.capLevelOnFPSDrop: false turns frame‑drop capping off; true runs hls.js's own controller instead, whose cap a later player‑size or maxBitrate recompute can overwrite.

  • A frozen picture on Safari is reloaded. The native engine (Safari, iPhone, iPad) watches the playhead and the buffered media under it: when neither has moved for 8 s while the page is visible, the element is playing and the browser is online, the stream is reloaded at the live edge. WebKit's native HLS has a freeze it never leaves by itself: the playhead stops, the buffer stops growing, nothing decodes and no error is raised. On production iPhone Safari (8 days to 2026-11-04) that happened 2.31 times per watch-hour, none recovered, and viewers paused or left after a median 24 s. Twice per 30 s of healthy playback; a slow start, a seek, a pause, a hidden tab and an offline browser never count. On a FairPlay stream the reload detaches the element's keys first, so the reloaded stream asks for a new licence (a reload that kept the old keys failed to decode on Safari, in 2.28.x). Counted in stuckReloads; stuckReload: false turns it off.

  • A buffer hole hls.js cannot nudge across jumps to live. When hls.js gives up seeking the playhead over a hole in the buffer (its fatal bufferSeekOverHole, or a bufferStalledError after its nudge budget) on a live stream, the SDK restarts loading at the live edge, which is past the hole, with the media element, the buffer and the DRM key sessions still in place. Twice per 30 s of healthy playback, out of the same three-recovery budget the MediaSource rebuild uses; after that, and on VOD, the MediaSource is rebuilt as before, and the fourth consecutive failure is the fatal error it always was.

  • Futile catch‑up is stopped. hls.js speeds playback up (to 1.1×) whenever latency sits above the target, and only lowers its ambition after a counted rebuffer. On an edge that is itself seconds behind, a player that keeps a deeper buffer (Safari) can chase at full rate for a whole session without ever gaining a second, which viewers see as constant stutter. The SDK watches the chase on its 3 s tick: a chase at the full 1.1× that gains under 0.5 s of latency over the next three ticks (12 s in all) moves the target up to where playback actually is (never closer than 1 s to the drift ceiling), and the rate drops back to 1.0×. One‑way for the session; targetLatencySeconds reflects the move and liveRetargets counts them. A rate the host sets itself is ignored.

  • Far‑from‑origin sessions get more buffer, nobody else does. The origin is in Frankfurt and the edges are local, so a viewer in South America, Canada/ Mexico or APAC pays a 250–310 ms cross‑continent fetch (p99 ~580 ms) for every part their edge misses, against ~44 ms in Europe; with 0.5 s parts the fetch cycle outruns the cadence, the 2 s buffer drains, and 37–50% of those sessions stalled at least once (3–13% rebuffer, against under 1% in the US and Europe, measured 2026‑10‑30). Longer parts or WebRTC would cost every viewer latency, so instead the player watches its own part fetches (adaptiveHoldBack, on by default): the first‑byte time of each part the playlist had already announced, as a share of the part's duration, over a 10 s window. A window whose p95 is at or above 60% (300 ms on a 0.5 s part) and whose median is at or above 40% (200 ms), two 3 s ticks running, steps the target up 0.5 s, up to 3.5 s (adaptiveHoldBackCeiling): a session that stalls drifts to ~6 s anyway, so a steady 3.5 s is the better trade for a latency‑sensitive viewer. A p95 under 40% for 60 s steps it back down, one step per minute, never below liveLatencyTarget. A session whose fetches are fast never moves; neither does one whose link is merely slow (transfer time is ABR's problem, so only the first byte counts), nor on a preload‑hint request (it blocks until the part exists, so its timing is production, not the path). A target the futile catch‑up watchdog raised, or hls.js raised after a stall, is never lowered. A browser reporting navigator.connection.rtt ≥ 300 ms starts one step up as soon as the stream is seen live, without waiting for evidence. Every move fires latencytargetchange with its reason, counts in holdBackSteps, and shows in targetLatencySeconds (and the QoE heartbeat's target latency). adaptiveHoldBack: false turns it off.

Migration note: the default liveLatencyTarget dropped from 3 s to 2 s. Nothing to change: the drift ceiling stays 12 s and the ABR reaction budgets are derived from the target, so they tighten with it automatically. Expect playback ~1 s closer to live. If you were relying on the old behaviour, pass liveLatencyTarget: 3 explicitly.

Migration note: liveCatchUpRate was removed as a public option; the catch‑up rate (1.1×) is now managed internally alongside the drift ceiling. If you set it before, drop it; reach for hlsConfig.maxLiveSyncPlaybackRate only if you genuinely need to override the rate.

Player ​

ts
interface Player {
  readonly state: PlayerState;
  readonly descriptor: StreamDescriptor | null;
  readonly offline: boolean; // the browser reports no network (navigator.onLine === false); see Connectivity
  play(): Promise<void>;
  pause(): void;
  setMuted(muted: boolean): void;
  setVolume(volume: number): void; // 0..1 (clamped)
  getStats(): PlaybackStats;
  // Track & quality control (empty/no-op on the native engine, which does ABR itself):
  getQualityLevels(): QualityLevel[];
  getCurrentQuality(): number; // -1 = auto
  setQuality(index: number | 'auto'): void;
  setMaxBitrate(bitrate: number | null): void;
  getAudioTracks(): AudioTrackInfo[];
  setAudioTrack(id: number): void;
  getTextTracks(): TextTrackInfo[];
  setTextTrack(id: number): void; // -1 = disable captions
  seekToLive(): void;
  enterPictureInPicture(): Promise<void>;
  exitPictureInPicture(): Promise<void>;
  enterFullscreen(): Promise<boolean>; // element FS on the player container; iPhone → video-native. false = no mechanism
  exitFullscreen(): Promise<void>; // element or video-native; safe when not fullscreen
  fullscreenSupported(): boolean; // false = permissions policy blocks it (iframe without allow=fullscreen) or no mechanism; optimistic before media loads on iPhone
  retry(): Promise<void>; // recover from an error (re-resolve + re-attach)
  reload(): Promise<void>; // re‑resolve playback (refreshes the license URL) + re‑attach
  on<E extends PlayerEvent>(event: E, cb: (payload: PlayerEventMap[E]) => void): () => void;
  destroy(): void;
}

on(...) returns an unsubscribe function. Call destroy() to tear down hls.js, detach and clear listeners, and release the media element; the player is inert afterward (play/pause/etc. become no-ops).

Notes:

  • reload() rejects (and emits error, setting state to error) if the re-resolution fails, so await it or attach a .catch.
  • play() resolves even when the browser blocks autoplay; rely on the playing state / error event (not play()'s return value) to determine the outcome.

Player events ​

on(event, cb): the payload type depends on the event (PlayerEventMap):

EventPayloadFires when
readyvoidThe manifest is parsed and the player is attached.
waitingWaitStateArmed and waiting for go‑live. On the polling path it fires per poll with the countdown; on the SSE arming path it fires once, just after createPlayer resolves (with ttkMs when the server sent a kickoff time).
playingvoidPlayback is progressing.
bufferingvoidThe player is rebuffering.
pausedvoidPlayback is paused.
endedEndedReason | undefinedThe live stream ended; playback stops and the last frame is kept. The payload says why: 'interrupted' (the match is still running, and its stream dropped, so show "reconnecting", never "ended"; the player rejoins by itself) or 'match_ended' (a real end). undefined = the end came from the HLS layer (an #EXT-X-ENDLIST, or the staleness watchdog on either engine: a live playlist that stopped advancing for 12 s), or a server predating the field; treat it as a real end unless a reason follows: the first server reason refines a reason-less end (an ENDLIST that beats the push), firing ended again with it. While the live-state push is fresh (a frame within the last 60 s) and last said live, a watchdog end is not delivered: the player fires a warning (UNAVAILABLE, "reloading instead of ending") and reloads the stream instead, at most twice per 10 minutes; the third ends as before. Fires again with 'match_ended' if an interruption later turns out to be the end, so don't latch on the first one. Also readable any time as player.endedReason.
errorPlaybackErrorA fatal error occurred (playback stopped).
warningPlaybackErrorA non-fatal condition (e.g. FairPlay passthrough, a failed license refresh, QoE beacons disabled because the endpoint could not be derived — see analytics — or QoE beacons refused by the page's Content-Security-Policy, naming the origin to add to connect-src). Playback continues.
autoplayblockedvoidThe browser blocked autoplay (NotAllowedError). Show a tap-to-play / tap-to-unmute affordance, then call player.play() from the gesture.
qualitychangenumberActive rendition changed (level index, -1 = auto).
audiotrackchangenumberActive audio track changed (track id).
texttrackchangenumberActive text track changed (track id, -1 = off).
pipchangebooleanPicture-in-Picture entered (true) or exited (false).
latencytargetchangeLiveTargetChangeThe SDK moved the live‑sync target itself (hls.js engine): the adaptive hold‑back stepped it up for slow part fetches or down for fast ones, a high browser‑reported RTT started the session a step up, or a futile catch‑up parked it where playback is. Never for your own liveLatencyTarget.
statsPlaybackStatsPeriodic stats sample (statsIntervalMs).
statechangePlayerStateAny state transition.
offlinevoidThe browser reported it lost its network (the window's offline event). state is unchanged; player.offline is now true. See Connectivity.
onlinevoidThe browser reported its network is back (the window's online event). The player resumes on its own: a parked hls.js loader restarts at once, and a fatal error that happened while offline (or any NETWORK error) is retried, the same re-resolve as retry().

Connectivity ​

The player acts on the browser's own network signal, navigator.onLine and the window's online/offline events, on the offline side only: false is reliable (wifi off, airplane mode, cable out), while true only means "not known to be offline" (a captive portal or a dead upstream still reads as online), so a failure while "online" keeps its ordinary retry path.

What happens on a network loss, by layer:

  • hls.js engine: the browser's offline event engages a hold at once: the end-of-stream and starvation watchdogs stand down (a playlist that cannot be fetched is not a stream that ended), and a fatal network error with no HTTP status parks the loader instead of spending the five-attempt retry budget. The hold keys off the browser's signal because hls.js itself may never raise a fatal error during an outage: measured in Chromium, it sits in its own playlist-retry backoff for the whole of a 20 s loss. The online event releases the hold, refunds the budget and restarts the loader right away, with hls.js, the buffer and the DRM key sessions all still in place: measured in Chromium against a local live stream, the offline card is up 5 ms after the loss and playback is back 120 ms after the link returns, through one resolve for the whole session. A failure that carries a status is the origin's answer and is never parked.
  • Native engine (Safari): the element reports one opaque error for everything; while the browser says offline it is typed NETWORK, and the managed player re-attaches on online.
  • Managed player: emits offline/online, exposes player.offline, and on online retries a session that had already failed by then, whether the resolve threw NETWORK, the native element errored, or the hls.js budget was spent before the browser noticed. Terminal codes (GONE, NOT_FOUND, INVALID_URN, UNAUTHORIZED, GEO_DENIED, DRM_DEVICE_REVOKED) are never retried. The retry is the same re-resolve as retry(), so a failed one lands on the error card as usual.
  • Control bar: shows the offlineMessage card over the error and reconnecting cards while player.offline is true, with no Retry button. The ended card and the pre-play cards (the play button, the pre-live "Starting soon…" wait) are never covered.

An hls.js network failure with no HTTP status (no route, DNS, CORS, a reset) is reported as NETWORK (earlier releases reported INTERNAL). One that carries a status is the origin's answer and keeps the status-derived code.

Controls & theming ​

The managed player ships a built-in, fully skinnable control bar. By default (controls: 'custom') it wraps your <video> in a .havik-player container and renders the Oddin-branded UI: a center play/overlay, a seek bar (VOD only; a live stream shows none, see below), play/pause, volume, a live badge + go-live, quality / audio / subtitle menus, Picture-in-Picture, fullscreen, a buffering spinner, and branded status cards for the stopped/pre-play states: ended ("This stream has ended"), fatal error (message + Retry when retryable), pre-play (poster + play CTA), and armed-waiting ("Starting soon…"), so a finished or failed stream never leaves a frozen frame behind a dead play button. A GEO_DENIED error (the match is booked for your key but not playable in the viewer's country) gets its own copy, "This match isn't available in your country (RU)", naming the country the server saw, and no Retry button: a retry would be refused again. A DRM_DEVICE_REVOKED error (the license server refuses this device's DRM client) likewise gets "This device can't play protected video" and no Retry. A DRM_CLIENT error whose detail is keySystemNoAccess (the browser has no usable Widevine) gets "This browser can't play protected video" with the way out named, and one whose detail is keySystemStatusOutputRestricted (no HDCP on the display path) gets "Protected video can't be shown on this display"; both keep Retry. The cards pick up theme.logoUrl and the theme colors; customise the copy with endedMessage/interruptedMessage/errorMessage/offlineMessage (an errorMessage replaces the GEO_DENIED, DRM_DEVICE_REVOKED and DRM_CLIENT copy too), or set statusOverlays: false to drive your own end/error UI from the player events. It auto-hides during playback, supports keyboard shortcuts (space/k play-pause, m mute, f fullscreen, c captions, l go-live, arrows seek/volume), and is fully keyboard- and screen-reader-accessible. On a mouse, one click on the picture plays/pauses. On touch, a single tap shows or hides the bar and a double tap plays/pauses, so bringing the controls back on a phone never pauses the stream.

Fullscreen on iPhone: iPhone Safari has no element Fullscreen API, so the fullscreen button there enters the video-native fullscreen (webkitEnterFullscreen): the YouTube-style player with native iOS controls. The custom control bar, watermark, and overlays are not shown inside it; the viewer exits with the native Done button. Video-native fullscreen only exists once media is loaded, so on iPhone the button takes effect after playback has started (a tap on the pre-play poster is a no-op there). Everywhere else (desktop, Android, iPad) the button uses element fullscreen and keeps the branded controls.

Where fullscreen cannot work, the button is not shown and the f shortcut is inert, the same gate the Picture-in-Picture button has: a cross-origin iframe whose allow list omits fullscreen (the browser reports document.fullscreenEnabled === false), or a webview with no fullscreen mechanism at all. So an operator who must block fullscreen on an embed drops it from the iframe's allow attribute and needs no custom control bar. The decision is re-made on the video's loadedmetadata, which is when iPhone first reports whether its video-native presentation exists, so on iPhone the button is still shown (and inert, as above) until playback has started.

ts
type Controls = 'custom' | 'native' | 'none';
ValueBehaviour
'custom'Default. The branded, themeable Havik control bar.
'native'The browser's built-in <video controls> UI. No wrapper element is added.
'none'No controls. Drive the player entirely through its API (build your own).

Content-Security-Policy ​

The custom control bar injects one <style> tag into the page <head>. A page whose style-src has no 'unsafe-inline' blocks that tag, and the controls render unstyled. Pass the page's nonce as cspNonce, and the tag carries it:

ts
await createPlayer({
  video,
  env: 'integration',
  matchUrn: 'od:match:1234',
  credential: { apiKey: 'pk_test_…' },
  cspNonce: 'r4nd0mN0nce',
});
// with  Content-Security-Policy: style-src 'nonce-r4nd0mN0nce'

The rest of the SDK needs no inline style: the theme is applied through CSS variables set from JavaScript, which style-src allows. With controls: 'native' or 'none', nothing is injected and no nonce is needed.

Re-skin the custom bar in one of two ways; both set the same CSS variables, so they're interchangeable:

1. Pass a theme (merged over the Oddin defaults; omitted keys keep the brand value):

ts
await createPlayer({
  video,
  baseUrl,
  matchUrn,
  credential: { apiKey },
  theme: {
    accent: '#14b8a6', // play button, seek fill, live dot, focus ring
    accentText: '#04201c', // text/icon sitting on the accent
    surface: '#0f172a', // control-bar + menu background
    logoUrl: 'https://cdn.example.com/logo.svg', // optional corner watermark
  },
});

2. Or override the CSS variables in your own stylesheet (handy for theming many players, dark/light switching, or matching an existing design system):

css
.havik-player {
  --havik-accent: #14b8a6;
  --havik-accent-text: #04201c;
  --havik-surface: #0f172a;
  --havik-radius: 4px;
}

HavikTheme ​

Each theme key maps to a --havik-* CSS variable on the .havik-player element:

HavikTheme keyCSS variableDefault (Oddin)Used for
accent--havik-accent#E1B600 (gold)Play button, seek fill, live dot, focus
accentText--havik-accent-text#1B1C23 (navy)Text/icon on the accent
background--havik-bg#0e0f13Letterbox / behind-video background
surface--havik-surface#1B1C23Control-bar + menu surface
surfaceMuted--havik-surface-muted#2a2c36Hover / active surface
text--havik-text#ffffffPrimary text / icons
textMuted--havik-text-muted#9aa0adSecondary text (timestamps, inactive)
border--havik-borderrgba(255, 255, 255, 0.1)Hairline borders
radius--havik-radius8pxCorner radius for buttons / menus
fontFamily--havik-fontsystem UI stackControl-bar font
logoUrl--havik-logo— (none)Optional corner watermark (a URL)

The default theme (ODDIN_THEME) and the applyTheme(root, theme?) helper are exported from the package root if you need the values directly or want to skin a container yourself:

ts
import { applyTheme, ODDIN_THEME, type HavikTheme } from '@oddin-gg/havik-player';

applyTheme(myElement, { accent: '#14b8a6' }); // writes --havik-* vars

PlayerState ​

ts
type PlayerState =
  'idle' | 'waiting' | 'loading' | 'playing' | 'buffering' | 'paused' | 'ended' | 'error';

Mode B: Bring your own player ​

The SDK resolves the stream and gives you DRM helpers; you own the <video> element and the playback engine.

resolveStream ​

ts
function resolveStream(opts: ResolveOptions): Promise<StreamDescriptor>;

Resolves a match into a StreamDescriptor. With waitForLive, it polls (server‑paced) until the stream is live, then resolves.

ts
const credential = { apiKey: 'pk_test_…' };
const stream = await resolveStream({
  baseUrl: 'https://feed-dev.oddin-video.gg',
  matchUrn: 'od:match:1234',
  credential,
  waitForLive: true,
});
// stream.manifestUrl, stream.drmEnabled, stream.drm?.widevine?.licenseUrl, …

ResolveOptions ​

OptionTypeDefaultDescription
baseUrlstring—Required. API base URL.
matchUrnstring—Required. The match to resolve.
credentialCredentialSource—Required.
waitForLiveWaitForLive—Poll until live before resolving.
signalAbortSignal—Cancel the resolution (and any live wait).

baseUrlForEnv ​

ts
function baseUrlForEnv(env: 'integration' | 'production'): string;

The API base URL for a named environment. integration is the shared pre-production stack, production the production one; they are separate deployments, not aliases.

Mode A takes env directly, so this is for Modes B and C, which still take a baseUrl. Call it rather than copying a hostname into your own config:

ts
const stream = await resolveStream({
  baseUrl: baseUrlForEnv('production'),
  matchUrn: 'od:match:1234',
  credential: { apiKey: 'pk_live_…' },
});

Throws a PlaybackError (INTERNAL) on any other value, rather than returning undefined. Callers reach it from plain JavaScript where the type gives no protection, and a silent undefined becomes a relative URL against the embedding page.

licenseRequestHeaders ​

ts
function licenseRequestHeaders(
  descriptor: StreamDescriptor,
  credential: Credential,
  opts?: LicenseHeaderOptions,
): Record<string, string>;

Returns the headers your player must attach to the DRM license POST:

x-api-key:    <your api-key>      // same key used to resolve playback
X-Match-Urn:  <descriptor.matchUrn>
X-Device-Id:  <persistent device id>
Content-Type: application/octet-stream
X-User-Id:    <opts.userId>       // only when provided

The license URL itself (descriptor.drm.widevine.licenseUrl) must be POSTed verbatim with the raw EME challenge bytes as the body. LicenseHeaderOptions:

OptionTypeDescription
deviceIdstringOverride the persistent device id (defaults to getDeviceId()).
userIdstringForwarded as X-User-Id.

Example: wiring into hls.js yourself ​

ts
import Hls from 'hls.js';
import { resolveStream, licenseRequestHeaders } from '@oddin-gg/havik-player';

const credential = { apiKey: 'pk_live_…' };
const stream = await resolveStream({ baseUrl, matchUrn, credential, waitForLive: true });
const headers = licenseRequestHeaders(stream, credential);

const hls = new Hls({
  emeEnabled: stream.drmEnabled && !!stream.drm?.widevine,
  drmSystems: stream.drm?.widevine
    ? { 'com.widevine.alpha': { licenseUrl: stream.drm.widevine.licenseUrl } }
    : undefined,
  drmSystemOptions: {
    videoRobustness: 'SW_SECURE_DECODE',
    audioRobustness: 'SW_SECURE_CRYPTO',
    videoEncryptionScheme: 'cbcs',
    audioEncryptionScheme: 'cbcs',
  },
  // EME license requests route through licenseXhrSetup (NOT xhrSetup):
  licenseXhrSetup: (xhr) => {
    for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);
  },
  lowLatencyMode: true,
});
hls.loadSource(stream.manifestUrl);
hls.attachMedia(videoElement);

Fullscreen helpers ​

ts
function enterVideoFullscreen(video: HTMLVideoElement, container?: HTMLElement): Promise<boolean>;
function exitVideoFullscreen(video: HTMLVideoElement, container?: HTMLElement): Promise<void>;
function videoFullscreenActive(video: HTMLVideoElement, container?: HTMLElement): boolean;
function fullscreenSupported(video: HTMLVideoElement, container?: HTMLElement): boolean;

Fullscreen with the platform quirks handled, so your own fullscreen button works everywhere the managed control bar's does. enterVideoFullscreen walks a capability ladder: standard element fullscreen on container (pass your player wrapper to keep your own controls visible; defaults to the video), the webkit-prefixed variant (older iPad/macOS Safari), and finally video.webkitEnterFullscreen(): iPhone Safari has no element Fullscreen API at all, so the only fullscreen there is the video-native presentation with native iOS controls (your DOM is not visible inside it, and it only takes effect once media is loaded). Call it from a user gesture. It resolves false when the platform has no mechanism at all (some webviews) so you can hide your button; a denied request (permissions policy) rejects.

exitVideoFullscreen leaves whichever presentation is active (video-native first; it reports only through the video, never the document), is safe to call when not fullscreen, and is scoped to your video's presentation: an unrelated element's fullscreen elsewhere on the page is left alone. videoFullscreenActive tells you whether your video's presentation is currently fullscreen. fullscreenSupported is the pre-flight for your button: false when a request is known to fail: the element API is there but the document reports fullscreenEnabled === false (permissions policy; an iframe without fullscreen in allow), or media is loaded and the platform has no mechanism at all. It stays true before media loads where no element API exists (iPhone cannot say yet), so re-check it on loadedmetadata. Pass the same container to all four. For fullscreen state changes, listen to fullscreenchange / webkitfullscreenchange on the document and webkitbeginfullscreen / webkitendfullscreen on the video; the last two are the only signal for iPhone's video-native fullscreen.

detectDrmSupport ​

ts
function detectDrmSupport(opts?: {
  systems?: DrmSystem[]; // default: ['widevine', 'fairplay'], probed in order
  timeoutMs?: number; // OVERALL budget for the whole call, default 5000
}): Promise<DrmSupportResult>;

interface DrmSupportResult {
  verdict: 'supported' | 'no-cdm' | 'insecure-context' | 'blocked-by-policy' | 'probe-timeout';
  system?: DrmSystem; // first working system, when supported
  detail: Partial<Record<DrmSystem, string>>; // per-system outcome, for support bundles
}

Answers "can protected playback work in this browser at all?" so you can show an accurate message instead of a black player. It probes requestMediaKeySystemAccess and createMediaKeys() per system (access alone is not proof), with configs matching what the engine will actually request, bounded by a timeout. It never rejects.

Rules of use:

  • Call it lazily, cache the verdict yourself: only once you know the content is DRM‑protected (descriptor.drmEnabled). The EME spec allows the probe to trigger consent prompts or CDM downloads, and results are not memoized; never run it on page load, and never probe for a clear stream.
  • Probe, don't UA‑sniff. The verdict is the playability gate; use the UA only to word the message.
  • insecure-context means EME is unavailable by spec, typical when testing over http://<LAN‑IP>; localhost is fine.
  • blocked-by-policy means an embedding problem (an iframe missing allow="encrypted-media"), not an unsupported browser, so surface it to the integrator, not the viewer.
  • supported is necessary, not sufficient: licensing, CORS onboarding and packaging still apply.

getDeviceId / clearDeviceId ​

ts
function getDeviceId(): string;
function clearDeviceId(): void;

getDeviceId() returns a persistent per‑device id (a random UUID stored in localStorage, regenerated only if storage is unavailable). It is sent as X-Device-Id on every DRM license request.

Privacy: the device id is a stable, cross‑session identifier (personal data under GDPR/ePrivacy). Disclose it in your privacy policy and offer a reset: clearDeviceId() removes the stored id so the next call generates a fresh one.

clearRememberedBandwidth ​

ts
function clearRememberedBandwidth(): void;

Forgets the bandwidth the player remembered for this device (the rememberBandwidth option, localStorage key havik.player.bandwidth). The next session starts from the conservative ~1 Mbps estimate again. The record holds only an estimated speed and a timestamp per connection type; offer it beside clearDeviceId() in a "reset player data" control.

fetchCatalog ​

ts
function fetchCatalog(opts: FetchCatalogOptions): Promise<Catalog>;

Fetches the metadata catalog (tournaments → matches). No manifest or DRM data is included; use resolveStream for playback. Supports a conditional refresh via ETag.

ts
const catalog = await fetchCatalog({ baseUrl, credential, status: ['live', 'upcoming'] });
// poll cheaply later with the previous etag:
const next = await fetchCatalog({ baseUrl, credential, etag: catalog.etag });
if (next.notModified) {
  /* nothing changed */
}

flattenMatches(catalog) returns all matches as a flat CatalogMatch[].

FetchCatalogOptions ​

OptionTypeDescription
baseUrlstringRequired.
credentialCredentialSourceRequired.
signalAbortSignalCancel the request.
etagstringPrior ETag for a conditional GET (notModified: true on 304).
statusMatchLiveStatus | MatchLiveStatus[]Filter by status.
sportstringFilter by sport.

watchStatus ​

ts
function watchStatus(opts: WatchStatusOptions): StatusWatcher;

Polls a single match's live status and fires onChange once on first read and then on every change of the status, the teams (a logo resolved later) or the planned start; unchanged polls stay silent. Returns a StatusWatcher with stop(). For a push channel (no polling) use subscribeLiveState instead; watchStatus is the zero-dependency polling alternative when the SSE endpoint isn't available.

ts
const watcher = watchStatus({
  baseUrl,
  matchUrn,
  credential,
  onChange: (m) => {
    if (m.status === 'live') startPlayback();
  },
});
// later: watcher.stop();

WatchStatusOptions ​

OptionTypeDefaultDescription
baseUrlstring—Required.
matchUrnstring—Required.
credentialCredentialSource—Required.
onChange(status: MatchStatus) => void—Required. Fired on first read, then on any status, teams or start change.
onError(err: PlaybackError) => void—Fired on a poll error; polling continues, except on NOT_FOUND, GEO_DENIED, GONE or INVALID_URN: the watcher stops itself and this is its last call.
intervalMsnumber10000Poll interval (floored at 2000).

subscribeLiveState ​

ts
function subscribeLiveState(opts: SubscribeLiveStateOptions): LiveStateSubscription;
function deriveEventsBaseUrl(baseUrl: string): string | undefined;

Push-based live state over Server-Sent Events (events.<domain>/v1/events/{urn}). The managed player uses this automatically (the liveStateEvents option) to go live the instant a match starts, without polling /v1/playback, and to detect end-of-stream instantly; BYO players can use it directly. state mirrors the /v1/playback outcome ladder:

statemeaningmaps to /v1/playback
liveserveable now, so play200 OK
upcomingscheduled, not serving yet425 Too Early (with liveStartsAt)
pendingkickoff passed, stream being packaged — live follows within seconds to minutes425 Too Early (no liveStartsAt)
endedwas live; media stopped503
goneended past the catchup window410 Gone

An ended event also carries a reason: 'interrupted' (the match is still running; only its stream dropped, so a BYO player should show "reconnecting" and expect play to resume) or 'match_ended' (a real end). It is absent for other states, and absent entirely from servers predating it, so read undefined as "assume a real end". A stream that is interrupted and whose match later finishes sends a second ended event with the reason moved interrupted → match_ended; the state never changes, so don't stop listening after the first.

Uses fetch (not native EventSource, which can't set the x-api-key header), reconnects with backoff, and replays the current state on connect. Every event is also reported via onAlive (including heartbeats) so callers can treat the stream as healthy. A subscription problem is non-fatal; it retries in the background. Two answers are special, both reported to onError as a LiveStateHttpError (status, terminal): an HTTP 410 means the match is gone for good and the subscription stops (terminal: true); an HTTP 404 means the match is not in the catalog now (it ended and was dropped, or it is not listed yet) and the retry moves to a slow lane, notFoundRetryMs (default 5 min), so a tab left open on a finished match costs one request every five minutes instead of one every 15 s, while a match listed late is still picked up without a reload.

A connection can also go silent without closing (a black-holed socket after a laptop sleep, a NAT rebind, a half-closing proxy). Nothing in the reconnect path above catches that on its own, so the subscription would stay permanently dead and silent, missing a real end-of-match push without surfacing anything to the caller. An idle watchdog covers it, in both phases: idleTimeoutMs spent waiting for response headers, or idleTimeoutMs without a byte on an open connection, tears that request down, reports it via onError, and reconnects through the normal backoff. Both phases matter, because the reconnect the watchdog triggers goes out over a network that just changed, which is exactly the request most likely to hit a black hole of its own. The default (45s) is two missed 20s server heartbeats.

ts
import { subscribeLiveState, deriveEventsBaseUrl } from '@oddin-gg/havik-player';

const sub = subscribeLiveState({
  eventsBaseUrl: deriveEventsBaseUrl(baseUrl)!, // e.g. https://events.<domain>
  matchUrn,
  credential,
  onState: (ev) => {
    if (ev.state === 'live') startPlayback(); // then resolveStream()/createPlayer()
    if (ev.state === 'ended' || ev.state === 'gone') stopPlayback();
  },
});
// later: sub.close();

SubscribeLiveStateOptions ​

OptionTypeDefaultDescription
eventsBaseUrlstring—Required. SSE base, e.g. from deriveEventsBaseUrl(baseUrl).
matchUrnstring—Required.
credentialCredentialSource—Required.
onState(ev: LiveStateEvent) => void—Required. Initial snapshot on connect + every transition.
onError(err: unknown) => void—Subscription error; the client keeps retrying, except: an HTTP answer arrives as a LiveStateHttpError (status, terminal), a 410 is terminal and stops the subscription, a 404 moves it to the notFoundRetryMs lane.
onAlive() => void—Liveness tick on every received frame (incl. heartbeats).
minBackoffMsnumber1000Reconnect backoff floor.
maxBackoffMsnumber15000Reconnect backoff ceiling.
idleTimeoutMsnumber45000Silence (awaiting headers, or bytes) before reconnecting; 0 off.
notFoundRetryMsnumber300000Retry interval after an HTTP 404 (match not in the catalog now); not floored by maxBackoffMs.

isLowLatencyManifest ​

ts
function isLowLatencyManifest(playlistText: string): boolean;

Utility: returns true if an HLS playlist body contains low‑latency tags (EXT-X-PART-INF / EXT-X-PART / EXT-X-PRELOAD-HINT).


Mode C: Iframe embed ​

Embed a hosted player page and control it over postMessage. This is the lowest‑touch integration and isolates playback in its own browsing context.

mountEmbed ​

ts
function mountEmbed(opts: MountEmbedOptions): EmbedHandle;

Creates an iframe pointing at the hosted embed page, threads the configuration, and sets up an origin‑verified postMessage bridge.

ts
const embed = mountEmbed({
  container: document.querySelector('#player')!,
  src: 'https://player-dev.oddin-video.gg/embed/',
  baseUrl: 'https://feed-dev.oddin-video.gg',
  matchUrn: 'od:match:1234',
  onEvent: (msg) => console.log(msg),
});

embed.play();
embed.setMuted(false);
// embed.destroy();

MountEmbedOptions ​

OptionTypeDescription
containerHTMLElementRequired. Element to mount the iframe into.
srcstringRequired. URL of the hosted embed page.
baseUrlstringRequired. API base URL (threaded to the iframe).
matchUrnstringRequired. Match to play.
apiKeystringDev only. Appended as a query param. In production the embed page injects the key server‑side, so omit this.
allowedFrameOriginstringOrigin of the embed page, used to verify its messages. Defaults to the origin of src (resolved against the current page when src is relative).
sandboxstringiframe sandbox value. Default allow-scripts allow-same-origin allow-presentation (keeps EME + fullscreen, blocks top-frame navigation and popups). The iframe is also mounted with referrerpolicy="no-referrer".
mutedbooleanStart muted.
onEvent(msg: FrameToHost) => voidCalled for every event from the iframe.

EmbedHandle ​

ts
interface EmbedHandle {
  readonly iframe: HTMLIFrameElement;
  play(): void;
  pause(): void;
  setMuted(muted: boolean): void;
  setVolume(volume: number): void;
  setQuality(index: number): void; // -1 = auto
  setMaxBitrate(bitrate: number | null): void;
  setAudioTrack(id: number): void;
  setTextTrack(id: number): void; // -1 = off
  seekToLive(): void;
  enterPip(): void;
  exitPip(): void;
  retry(): void;
  load(matchUrn: string): void; // switch to a different match
  on(cb: (msg: FrameToHost) => void): () => void; // returns unsubscribe
  destroy(): void;
}

Track lists arrive from the iframe as an oddin:tracks event (see below); use those to build a quality/caption menu, then drive selection with setQuality/setTextTrack/etc.

The embed page ​

A ready‑to‑host template lives in the repository at embed/index.html (loads the CDN bundle and calls bootEmbed()). To self‑host, serve a page that runs:

ts
import { bootEmbed } from '@oddin-gg/havik-player';
bootEmbed();

bootEmbed() reads its EmbedConfig from window.HAVIK_EMBED_CONFIG (server‑injected, preferred) or the URL query string, runs a managed player full‑bleed, and speaks the postMessage protocol. The api‑key is never accepted over postMessage; inject it server‑side in production.

EmbedConfig ​

Read by bootEmbed() in one of two mutually-exclusive modes: if window.HAVIK_EMBED_CONFIG is present (production) it is the only source; the query string is ignored entirely, so a tampered ?baseUrl= can't redirect the injected api-key. Otherwise (dev/demo) config comes from the query string. The postMessage bridge fails closed: with no parentOrigin, the embed neither accepts commands nor posts events.

FieldTypeDefaultDescription
baseUrlstring—Required. API base URL.
matchUrnstring—Required. Match to play.
apiKeystring—Required. Inject server‑side in production; query param is dev‑only.
parentOriginstring—Origin to post events to and accept commands from. Set this in production (mountEmbed sets it automatically). When absent, the iframe posts to * and skips the inbound origin check.
autoplaybooleantrueStart playback once ready.
mutedbooleantrueStart muted (recommended for autoplay).
waitForLiveWaitForLivetrueArm and auto‑play at go‑live.
analyticsboolean | { endpoint?: string }trueQoE beacons, forwarded verbatim to createPlayer. Injected config only — never read from the query string, so a link cannot redirect a session's beacons. havik-streams v0.10.0+ names the beacons host itself, so this is only needed against an older server: there, set { endpoint } when baseUrl is not a feed[-dev].<domain> host, since nothing can be derived and analytics is otherwise off. ⚠️ Against such a server, mountEmbed configures the page via query string, so it cannot carry this: a mountEmbed integration on a non-feed baseUrl has no way to enable beacons and must self-host the embed page instead.

postMessage protocol ​

Every message is filtered with isOddinMessage (anything not a recognized oddin: message is ignored). The host verifies event.origin against the embed page's origin on every message. The iframe verifies event.origin against its configured parentOrigin, and mountEmbed always sets this, so the bridge is origin‑verified end‑to‑end. If you self‑host the embed page and call bootEmbed() directly, always set parentOrigin (see EmbedConfig); without it the iframe accepts oddin: messages from any origin and posts events with target origin *.

Host → iframe (HostToFrame):

ts
{ type: 'oddin:play' } | { type: 'oddin:pause' }
{ type: 'oddin:setMuted'; muted: boolean } | { type: 'oddin:setVolume'; volume: number }
{ type: 'oddin:setQuality'; index: number } | { type: 'oddin:setMaxBitrate'; bitrate: number | null }
{ type: 'oddin:setAudioTrack'; id: number } | { type: 'oddin:setTextTrack'; id: number }
{ type: 'oddin:seekToLive' } | { type: 'oddin:enterPip' } | { type: 'oddin:exitPip' } | { type: 'oddin:retry' }
{ type: 'oddin:load'; matchUrn: string } | { type: 'oddin:destroy' }

Iframe → host (FrameToHost):

ts
{ type: 'oddin:ready'; protocol: number }            // protocol = PROTOCOL_VERSION
{ type: 'oddin:autoplayblocked' }
{ type: 'oddin:state'; state: PlayerState }
{ type: 'oddin:waiting'; retryInMs: number; attempt: number; phase: string }
{ type: 'oddin:tracks'; quality: QualityLevel[]; audio: AudioTrackInfo[]; text: TextTrackInfo[] }
{ type: 'oddin:qualitychange'; index } | { type: 'oddin:audiotrackchange'; id } | { type: 'oddin:texttrackchange'; id }
{ type: 'oddin:stats'; droppedFrames; latencySeconds?; bandwidthKbps?; levelHeight?; lowLatency?; isLive?; atLiveEdge? }
{ type: 'oddin:error'; code: PlaybackErrorCode; message: string; country?: string } // country: set with GEO_DENIED

The oddin:ready event carries the embed page's protocol version; mountEmbed warns on a mismatch with the host SDK (pin the embed page version to avoid CDN auto-update skew).

If you handle messages directly (rather than via EmbedHandle.on), filter them with isOddinMessage(event.data) and always check event.origin.


Reference ​

Errors ​

Every API rejection is a typed PlaybackError:

ts
class PlaybackError extends Error {
  readonly code: PlaybackErrorCode;
  readonly httpStatus: number; // 0 for NETWORK / ABORTED; see the table notes for TIMEOUT / DRM_CLIENT
  readonly retryAfterMs?: number; // set for TOO_EARLY / RATE_LIMITED / UNAVAILABLE
  readonly liveStartsAtMs?: number; // epoch ms; set for TOO_EARLY when the server included `liveStartsAt`
  readonly country?: string; // upper-case ISO 3166-1 alpha-2; set for GEO_DENIED
  readonly serverCode?: string; // the server's own code, when the body carried one (e.g. 'cdm_revoked', 'license_refused')
  readonly requestId?: string; // server correlation id, when present
  readonly detail?: string; // the engine's own name for the failure (an hls.js ErrorDetails value), when it supplied one
}
codeHTTPMeaningRetryable
INVALID_URN400Malformed match URN.No
NOT_FOUND404Unknown match or not entitled (indistinguishable by design).No
GEO_DENIED451The match is booked for your key, but a grant's country list excludes the viewer's country; country names it. A server without the 451 answers 404 NOT_FOUND for the same case.No
GONE410Ended and past the catch‑up window.No
TOO_EARLY425Upcoming; not live yet.Yes (via waitForLive)
UNAVAILABLE503Should be live; origin warming up.Yes
UNAUTHORIZED401Bad/absent api‑key.No
FORBIDDEN403Origin not allowed, DRM signature rejected, or a license refused for a reason the server did not name (serverCode: 'license_refused'); a real server 403.No⁴
DRM_DEVICE_REVOKED403The license server refuses this device's DRM client outright (a revoked Widevine certificate); the license 403 body carries cdm_revoked. The device is the problem, not the match, the key or the network.No³
DRM_CLIENT(lic.)²Client‑side DRM failure: no key system usable on this platform, a CDM/EME error, or license delivery failed without a server denial.Sometimes²
RATE_LIMITED429Per‑client request limit.Back off
INTERNAL5xxUnexpected server/SDK error.No
NETWORK0The network request failed (offline, CORS, DNS), including an hls.js media or playlist fetch with no HTTP status once the engine's retry budget is spent. Retried by the managed player on the browser's online event (see Connectivity).Yes (in the live‑poll loop)
TIMEOUT(last)¹waitForLive exceeded timeoutMs.No
ABORTED0Cancelled via AbortSignal.No

¹ TIMEOUT.httpStatus carries the status of the last error it was waiting on, typically 425 while waiting for an upcoming match, 503 while an origin warms up, or 0 if the timeout lands on a network failure.

² DRM_CLIENT.httpStatus carries the license/certificate HTTP status when one was involved (e.g. a 5xx after the SDK's license-retry budget is exhausted), else 0 (no usable key system, CDM/EME error, request never got a response). A genuine license 401/403 surfaces as UNAUTHORIZED/FORBIDDEN, never as DRM_CLIENT, so branch on the code, not on httpStatus, to tell a server rejection from a device that can't play DRM. The built-in error card still offers Retry (it re-resolves and re-attaches, which can recover a transient license failure); an unsupported device will simply fail the same way again. detail carries hls.js's own name for the failure: on keySystemNoAccess (the browser has no usable Widevine: a Chromium build without the CDM, a WebView, DRM switched off) the card says "This browser can't play protected video" and names the site setting and the browsers that work (Safari only when the stream carries FairPlay, since the hls.js engine is Widevine-only), and on keySystemStatusOutputRestricted (the display path refuses the key, no HDCP) it says "Protected video can't be shown on this display". Both keep Retry: Firefox asks the viewer to allow DRM on the first attempt, and a changed display is a retry away.

³ DRM_DEVICE_REVOKED is read off the body of a license 403: the DRM proxy answers {"error":"cdm_revoked"} when the license server refuses the device's DRM client (Widevine in practice; the FairPlay path reads the same body). Any other license 403 body (license_refused, a WAF page, nothing) stays FORBIDDEN; serverCode carries the body's code either way. It is terminal for that device: the built-in error card shows "This device can't play protected video" with no Retry, and the lapsed-URL recovery below is not spent on it. On the hls.js engine the body is read off the XHR hls.js attaches to its error; a caller-supplied hlsConfig.licenseXhrSetup does not change that. Tell the viewer to use another device or an up-to-date browser; there is nothing to fix on your side.

⁴ "Retryable" is whether a retry can succeed, and a FORBIDDEN request answered the same way will not. The built-in error card still offers Retry on FORBIDDEN (as it does on DRM_CLIENT), because one license 403 shape is recoverable: a signed URL whose exp lapsed is refreshed by the re-resolve Retry performs (the lapsed-URL handling below). A 403 with serverCode: 'license_refused' keeps that card unchanged; only DRM_DEVICE_REVOKED drops the Retry button, since the server named a cause no retry changes.

A lapsed signed license URL is handled before it reaches you. The licenseRefreshMs timer cannot run while the browser has the tab frozen (a long-hidden tab, a machine that slept), so the URL the player holds can carry an exp that has already passed. Two checks keep that from becoming a 403: on refocus, a lapsed URL is refreshed at once; and right before any Widevine license request, the player checks the held URL's exp and mints a fresh one first when it has lapsed (the request waits for the re-resolve, nothing else does). Should a stale request still reach the server (a refresh that failed, a viewer clock far behind), its 403 is recovered once by a re-resolve and re-attach (the same path as Retry), surfaced as a warning instead of ending the session; a second 403 before a key is usable on the fresh URL is fatal as usual. All three checks run on the viewer's clock and cover Widevine (hls.js) only: a device clock more than ~10 minutes slow still sees the plain fatal FORBIDDEN, and FairPlay (Safari) keeps its existing fatal path.

ts
import { PlaybackError } from '@oddin-gg/havik-player';
try {
  await resolveStream({ baseUrl, matchUrn, credential });
} catch (e) {
  if (e instanceof PlaybackError && e.code === 'NOT_FOUND') showUnavailable();
  if (e instanceof PlaybackError && e.code === 'GEO_DENIED') showBlockedIn(e.country); // e.g. "RU"
}

Data types ​

StreamDescriptor ​

The normalized playback credential.

ts
interface StreamDescriptor {
  matchUrn: string;
  protocol: 'hls';
  drmEnabled: boolean; // when false, no EME/CDM is needed
  manifestUrl: string; // unsigned HLS .m3u8
  drm?: DrmInfo; // present only when drmEnabled
  serverTime: string; // RFC3339
  liveStartsAt?: string; // present only while upcoming
  isLowLatency?: boolean; // filled by the player once detected
  // Present when the playback response carries an analytics sid. Mode B gets
  // the data only: no beacons are sent unless you send them. `endpoint` is the
  // server-named beacons origin (havik-streams v0.10.0+), kept only when it is
  // a bare https origin; beacons POST to `<endpoint>/v1/beacons`.
  analytics?: { sid?: string; endpoint?: string };
}

DrmInfo, WidevineInfo, FairPlayInfo, DrmSystem ​

ts
interface DrmInfo {
  widevine?: WidevineInfo;
  fairplay?: FairPlayInfo;
}
interface WidevineInfo {
  licenseUrl: string;
} // pre-signed; POST verbatim
interface FairPlayInfo {
  licenseUrl: string;
  certificateUrl: string;
}
type DrmSystem = 'widevine' | 'fairplay';

Credential, CredentialSource ​

ts
interface Credential {
  apiKey: string;
}
type CredentialSource = Credential | (() => Credential | Promise<Credential>);

Catalog, CatalogTournament, CatalogMatch, CatalogTeam ​

ts
interface Catalog {
  tournaments: CatalogTournament[];
  etag?: string;
  notModified: boolean; // true on a 304 conditional refresh
}
interface CatalogTournament {
  urn: string;
  name: string;
  sport: string;
  isOffline: boolean;
  matches: CatalogMatch[];
}
interface CatalogMatch {
  matchUrn: string;
  matchName: string;
  status: MatchLiveStatus;
  // The server's status string verbatim. Equals `status` for values this SDK
  // knows; carries the new value when the server's vocabulary has grown past
  // it — read this to act on a status the `MatchLiveStatus` union does not
  // name yet.
  statusRaw?: string;
  datePlannedStart?: string;
  tournamentUrn: string;
  tournamentName: string;
  sport: string;
  // The two sides, home first. Absent when no usable team survives parsing:
  // the server sent no `teams` (an older havik-streams), or every entry
  // lacked both a URN and a name. A team with a URN but no name IS kept.
  // `matchName` stays the display string; this is its structured form.
  teams?: CatalogTeam[];
}
interface CatalogTeam {
  urn: string; // competitor URN, e.g. "od:competitor:26406"; "" if the server sent a name only
  name: string;
  isHome: boolean;
  // An https image URL for the team logo, present only when the deployment
  // resolves logos and this team has one (most do). Can still fail to load —
  // always render a fallback for a missing or broken image. Logos are ~150 px
  // on the long side. Allow cdn.oddin.gg (and cdn.runestone.gg) in img-src.
  logoUrl?: string;
}

Parsing is tolerant: a non-array teams is ignored, entries with neither a URN nor a name are dropped, isHome is true only for a literal true, and a logoUrl that is not an absolute https: URL is dropped (an http: image is mixed content on an https page).

MatchStatus, MatchLiveStatus ​

pending is "kickoff has passed, the stream is being packaged": not playable yet, live expected within seconds to minutes. Unknown values still collapse to upcoming with the verbatim value in statusRaw.

ts
type MatchLiveStatus = 'upcoming' | 'pending' | 'live' | 'ended';
interface MatchStatus {
  matchUrn: string;
  matchName?: string;
  status: MatchLiveStatus;
  // The server's status string verbatim — see CatalogMatch.statusRaw.
  statusRaw?: string;
  datePlannedStart?: string;
  // The teams as of this report (see CatalogTeam). watchStatus fires again
  // when they change, so a logo resolved later is re-reported.
  teams?: CatalogTeam[];
}

PlaybackStats ​

ts
interface PlaybackStats {
  droppedFrames: number; // only grows for the session, even where the element's counter resets
  decodedFrames?: number; // TOTAL frames incl. dropped (ratio = droppedFrames / decodedFrames); also only grows
  latencySeconds?: number; // live-edge latency: playhead behind the newest known media (both engines; native omits it while paused)
  targetLatencySeconds?: number; // live-sync target latency; compare vs latencySeconds for drift
  bandwidthKbps?: number; // estimated bandwidth (hls.js engine)
  levelHeight?: number; // current rendition height
  lowLatency?: boolean; // whether LL-HLS was detected in the manifest
  isLive?: boolean; // current media playlist is live
  atLiveEdge?: boolean; // playback is at/near the live edge
  liveRetargets?: number; // times a futile catch-up moved the live target (hls.js engine)
  holdBackSteps?: number; // times the adaptive hold-back moved the live target, up or down (hls.js engine)
  fpsDownCaps?: number; // times quality was capped because the device dropped frames (hls.js engine)
  maxLevelHeight?: number; // highest rendition ABR may pick right now; absent when uncapped (hls.js engine)
  stallDownCaps?: number; // times a playback stall stepped the quality ceiling down (hls.js engine)
  stuckReloads?: number; // times a frozen playhead with a buffer that stopped growing was reloaded at live (native engine)
  capReason?: 'size' | 'bitrate' | 'fps' | 'stall'; // which SDK cap set maxLevelHeight: player pixel box, maxBitrate, frame drops, recent stall
}

LiveTargetChange ​

Payload of latencytargetchange.

ts
interface LiveTargetChange {
  targetSeconds: number; // the target hls.js now converges to
  previousSeconds: number; // the one it replaced
  reason: 'slow-fetches' | 'fast-fetches' | 'connection-rtt' | 'futile-chase';
}

QualityLevel, AudioTrackInfo, TextTrackInfo ​

ts
interface QualityLevel {
  index: number;
  width?: number;
  height?: number;
  bitrate: number;
  codecs?: string;
}
interface AudioTrackInfo {
  id: number;
  name: string;
  lang?: string;
  default: boolean;
}
interface TextTrackInfo {
  id: number;
  name: string;
  lang?: string;
}

Live-pickup options ​

WaitForLive ​

ts
type WaitForLive = boolean | WaitForLiveOptions;

Set to true for sensible defaults, or pass options:

OptionTypeDefaultDescription
timeoutMsnumberunboundedOverall budget before giving up with TIMEOUT.
floorMsnumber1000Minimum delay between polls (also the server minimum).
ceilMsnumber30000Maximum delay between polls inside the imminent window (see imminentMs). Far-from-kickoff polls are widened; see below.
kickoffAtnumber | string—Scheduled kickoff (epoch ms or ISO string). When given, the SDK widens long-tail polls automatically; see "Far-future polling".
imminentMsnumber600000Time-to-kickoff threshold for "imminent" (collapses to the tight [floorMs, ceilMs] band).
sanityFloorMsnumber300000Hard cap on any single sleep (so an early go-live / schedule change is caught within bounded latency). 5 min default.
jitterbooleantrueAdd up to +15% jitter (never polls faster than the server asks).
onState(state: WaitState) => void—Called before each wait.
Far-future polling ​

A viewer armed hours before kickoff would otherwise hammer /v1/playback every 30s for the entire long tail. When kickoffAt is set (or the server includes liveStartsAt on the 425 body; see Errors liveStartsAtMs), the poll cadence is widened to min(ttk / 10, sanityFloorMs) for the long tail and collapses to the tight [floorMs, ceilMs] range only inside the imminent window. Guards baked in: the server's Retry-After is always a floor (the server can tighten cadence near kickoff regardless), sanityFloorMs caps every single sleep so an early go-live is caught within ≤5 min, and a 200 resolves immediately at any point. Concretely, a match 2 h out now makes ≈30 polls instead of ≈240.

WaitState ​

ts
interface WaitState {
  phase: 'tooEarly' | 'unavailable' | 'rateLimited' | 'network';
  retryInMs: number; // time until the next poll
  attempt: number; // 1-based retry count
  elapsedMs: number; // wall-clock since the wait started
  ttkMs?: number; // time-to-kickoff used to compute this delay, if known
}

Advanced ​

These exports are for advanced/custom integrations.

  • pollToLive(attempt, cfg, signal?): the generic retry primitive behind waitForLive. Polls an arbitrary () => Promise<T>, retrying on retryable PlaybackErrors and honoring retryAfterMs.
  • isOddinMessage(data): type guard for the postMessage protocol.
  • ODDIN_THEME / applyTheme(root, theme?): the default control-bar skin and the helper that writes a HavikTheme onto an element as --havik-* CSS variables. See Controls & theming.

The internal engine seam (PlaybackEngine / EngineEvent) and one-shot helpers (resolvePlaybackOnce, resolveCredential) are not part of the public API and are excluded from the type declarations.


Onboarding & CORS ​

The api‑key is publishable: it is designed to live in browser JavaScript. Its protection is a server‑side allow‑list, so every origin you serve the player from must be onboarded before it will work:

  1. The key's allowed origins must include each origin running the player (and, for iframe embeds, the parent page origins).
  2. The DRM service's CORS allow‑list must include those same origins, or the cross‑origin license request fails its preflight and DRM never starts.
  3. Scope the key's entitlements to the tournaments you serve.

If you serve the player from a new domain, request it be added to the key's allow‑lists first. Key revocation is not instantaneous (validation is cached for a few minutes).

Never use a wildcard (*) origin allow‑list in production: it removes the only guardrail on a publishable key.

Service URL discovery ​

Don't hard‑code baseUrl in your application. Serve it from your own backend, and keep the backend current from the endpoint directory:

http
GET https://status-dev.oddin-video.gg/v1/endpoints.json

The document lists the current base URL per region and is served with Access-Control-Allow-Origin: *, so any backend or build pipeline can consume it. If an endpoint moves, most likely in regions with distinct internet regulations, the directory updates and your backend follows, with no app release or store re‑review.

Each environment publishes its own directory, and the same host carries the status page with live availability for every Havik service: https://status-dev.oddin-video.gg for integration, https://status.oddin-video.gg for production. Point your backend at the one whose baseUrl you serve.


Troubleshooting ​

SymptomLikely cause
NETWORK error on every call; preflight fails in devtoolsYour origin isn't on the key's allowed‑origins / DRM CORS allow‑list. See Onboarding.
UNAUTHORIZED (401)Wrong/expired api‑key, or wrong baseUrl environment (test vs prod key).
FORBIDDEN (403) on license requestsThe license URL was modified, or a different api‑key was used for the license than for playback. POST the URL verbatim with the same key. With serverCode: 'license_refused', the license server refused the request for a reason it did not name; include requestId when asking support.
DRM_DEVICE_REVOKED (403) on license requestsThe license server refuses this device's DRM client (a revoked Widevine certificate, typically an old browser build or a modified device). Nothing on your side or ours changes it; the viewer needs another device or an up-to-date browser. The built-in card says so and offers no Retry.
DRM_CLIENTThe device/browser can't play this DRM (no usable key system, CDM/EME error), or license delivery failed without a server denial. Check the console for the EME/CDM detail; call detectDrmSupport() to pre‑flight and message the viewer.
NOT_FOUND (404) for a match you can seeThe key isn't entitled to that tournament (404 is intentionally indistinguishable from "unknown").
GEO_DENIED (451) for a match you can seeThe key's grant for that match carries a country list that excludes the viewer's country (e.country). The viewer sees a card naming the country; the listings never show such a match to that viewer, so this only happens on a direct URN.
Player stays in waiting foreverThe match hasn't gone live yet; the SDK is polling. Set waitForLive.timeoutMs to bound it.
Autoplay doesn't startBrowser sound policy: set muted: true for autoplay, or start playback from a user gesture.
Black video on Safari with DRMCheck the console for an EME/CDM error; verify the origin is on the DRM CORS allow‑list. On very old Safari the native fallback plays only OS‑trusted passthrough.
Black video in Chrome/Firefox/Edge on iOSiOS has no Widevine CDM, and FairPlay availability outside Safari varies by WebKit build. Call detectDrmSupport(): on no-cdm, tell the viewer this browser can't play protected streams.
Black video, levelHeight/droppedFrames stuckCheck the browser console for an EME/CDM error and verify DRM CORS onboarding.

Include PlaybackError.requestId (when present) when contacting support; it correlates to server‑side logs.


Versioning & support ​

  • The package follows semantic versioning. Pin a version in production (npm and CDN).
  • TypeScript definitions ship with the package; the types are the source of truth for the API surface.
  • The bundled hls.js version is managed by the SDK; do not assume a specific version in managed mode.

For onboarding (api‑keys, origin allow‑lists, entitlements) and support, contact Oddin.

ISC licensed. Bundles hls.js (Apache-2.0).