@oddin-gg/havik-player 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/API.md DELETED
@@ -1,1200 +0,0 @@
1
- # Havik Player SDK — API Reference
2
-
3
- `@oddin-gg/havik-player` · HTML5 player SDK for Oddin live streams (LL‑HLS + DRM).
4
-
5
- This is the complete API reference. For a quick start, see the [README](../README.md).
6
-
7
- ---
8
-
9
- ## Contents
10
-
11
- - [Overview](#overview)
12
- - [Installation](#installation)
13
- - [Concepts](#concepts)
14
- - [What you need](#what-you-need)
15
- - [Credentials](#credentials)
16
- - [The play sequence](#the-play-sequence)
17
- - [Live pickup](#live-pickup)
18
- - [DRM](#drm)
19
- - [Browser support](#browser-support)
20
- - [Mode A — Managed player](#mode-a--managed-player)
21
- - [createPlayer](#createplayer)
22
- - [Player](#player) · [Player events](#playereventmap)
23
- - [Controls & theming](#controls--theming) · [HavikTheme](#haviktheme)
24
- - [Mode B — Bring your own player](#mode-b--bring-your-own-player)
25
- - [Mode C — Iframe embed](#mode-c--iframe-embed)
26
- - [Reference](#reference)
27
- - [Errors](#errors)
28
- - [Data types](#data-types)
29
- - [Live‑pickup options](#live-pickup-options)
30
- - [Advanced](#advanced)
31
- - [Onboarding & CORS](#onboarding--cors)
32
- - [Troubleshooting](#troubleshooting)
33
- - [Versioning & support](#versioning--support)
34
-
35
- ---
36
-
37
- ## Overview
38
-
39
- The SDK plays Oddin live streams in the browser over **Low‑Latency HLS** with
40
- **DRM**, and offers three integration modes:
41
-
42
- | Mode | Entry point | You provide | The SDK handles |
43
- | ----------------------------- | ----------------------------------- | ----------------------- | -------------------------------------------------- |
44
- | **A — Managed** | [`createPlayer()`](#createplayer) | a `<video>` element | hls.js, LL‑HLS, DRM/EME, retries, stats |
45
- | **B — Bring‑your‑own‑player** | [`resolveStream()`](#resolvestream) | your player + `<video>` | auth → catalog → playback resolution + DRM helpers |
46
- | **C — Iframe embed** | [`mountEmbed()`](#mountembed) | an iframe slot | everything, behind a `postMessage` API |
47
-
48
- All modes are exported from the package root and are fully typed (TypeScript
49
- definitions ship in the package).
50
-
51
- ---
52
-
53
- ## Installation
54
-
55
- **npm / bundlers:**
56
-
57
- ```bash
58
- npm install @oddin-gg/havik-player
59
- ```
60
-
61
- ```ts
62
- import { createPlayer, resolveStream, mountEmbed } from '@oddin-gg/havik-player';
63
- ```
64
-
65
- **Via `<script>` (CDN):** exposes a global `window.HavikPlayer`.
66
-
67
- ```html
68
- <script src="https://cdn.jsdelivr.net/npm/@oddin-gg/havik-player/dist/havik-player.global.js"></script>
69
- <script>
70
- const player = await HavikPlayer.createPlayer({ /* … */ });
71
- </script>
72
- ```
73
-
74
- > In production, pin a version in the CDN URL: `…/havik-player@X.Y.Z/dist/…`.
75
-
76
- The package is ESM, side‑effect‑free, and ships ES2022 output plus a self‑contained
77
- IIFE bundle for `<script>`/iframe use.
78
-
79
- ---
80
-
81
- ## Concepts
82
-
83
- ### What you need
84
-
85
- Two values are required to play any stream:
86
-
87
- - A **match URN** — identifies the event, e.g. `od:match:1234`.
88
- - A **publishable api‑key** — e.g. `pk_live_…` (production) or `pk_test_…` (test).
89
- The key must be configured with an **allowed origin list** that includes the
90
- origin your player runs on. See [Onboarding & CORS](#onboarding--cors).
91
-
92
- You also need the **API base URL**, e.g. `https://streams.oddin.gg`.
93
-
94
- ### Credentials
95
-
96
- Every API call carries your api‑key. Pass it as a [`Credential`](#credential), or as a
97
- function returning one — see [`CredentialSource`](#credentialsource). The function form is
98
- called per request, so it supports transparent refresh if you later move to
99
- short‑lived tokens.
100
-
101
- ```ts
102
- // static
103
- const credential = { apiKey: 'pk_live_…' };
104
-
105
- // dynamic (called per request)
106
- const credential = async () => ({ apiKey: await myTokenService.get() });
107
- ```
108
-
109
- ### The play sequence
110
-
111
- 1. **(Optional) Discover** live/upcoming matches — [`fetchCatalog()`](#fetchcatalog) — or
112
- watch a single match's status — [`watchStatus()`](#watchstatus).
113
- 2. **Resolve playback** — [`resolveStream()`](#resolvestream) returns a
114
- [`StreamDescriptor`](#streamdescriptor) with the manifest URL and DRM config.
115
- 3. **Play** — feed the descriptor to the managed player (Mode A) or your own player
116
- (Mode B).
117
- 4. **DRM licenses** are acquired automatically by the player's EME layer as the CDM
118
- encounters encrypted media.
119
-
120
- Match status is available as a **push** channel ([`subscribeLiveState`](#subscribelivestate),
121
- SSE) — used automatically by the managed player — with polling
122
- ([`watchStatus`](#watchstatus) / `waitForLive`) as the fallback. The authoritative
123
- signal that a stream is playable is still a successful playback resolution (not catalog
124
- status, which can briefly lead the stream going live).
125
-
126
- ### Live pickup
127
-
128
- A match scheduled to go live isn't immediately playable. The **`waitForLive`** option
129
- arms the player and attaches the **instant** the stream goes live, with zero manual
130
- action. By default it does this over the **push** channel (SSE,
131
- [`subscribeLiveState`](#subscribelivestate)): while connected it makes no
132
- `/v1/playback` requests, waits for the pushed `live`, then resolves once. If the SSE
133
- endpoint is unavailable it **falls back to polling** `TOO_EARLY` + the server's
134
- `Retry-After`. End-of-stream is detected automatically too — the player stops and
135
- fires `ended`. Set `liveStateEvents: false` to force polling-only.
136
-
137
- See [`WaitForLive`](#waitforlive) for tuning, and [`createPlayer`](#createplayer) /
138
- [`resolveStream`](#resolvestream) for usage.
139
-
140
- ### DRM
141
-
142
- - **Key systems:** Widevine (`com.widevine.alpha`) and FairPlay (`com.apple.fps`).
143
- PlayReady is not used (Windows/Edge play via Widevine).
144
- - **Container/encryption:** CMAF/fMP4, `cbcs`.
145
- - The playback descriptor's `drm.*.licenseUrl` values are **pre‑signed**. When you
146
- integrate your own player (Mode B), you must **POST to the license URL verbatim** —
147
- its signed query string is the access token; do not rewrite, re‑encode, or strip
148
- parameters. Use the **same api‑key** to resolve playback and to fetch licenses.
149
- The managed and iframe players handle this for you.
150
-
151
- > **FairPlay (Safari/iOS):** implemented on the hls.js engine. When the playback
152
- > descriptor carries FairPlay material and the platform is WebKit, the player
153
- > offers `com.apple.fps` alongside Widevine: hls.js fetches the application
154
- > certificate, handles the encrypted event, POSTs the SPC to the signed license
155
- > URL and applies the returned CKC. No configuration is needed beyond the same
156
- > api‑key used for playback.
157
- >
158
- > **iOS third‑party browsers (Chrome/Firefox/Edge on iOS):** iOS has no
159
- > Widevine CDM, so protected playback in these browsers depends entirely on
160
- > whether the WebKit build grants them FairPlay. Don't assume either way —
161
- > call [`detectDrmSupport`](#detectdrmsupport) and let the probe decide, so
162
- > viewers see an accurate message instead of a black player.
163
-
164
- ### Browser support
165
-
166
- | Browser | Engine | DRM |
167
- | -------------------------------- | --------------------- | -------------------------------------------------- |
168
- | Chrome, Edge (desktop & Android) | hls.js | Widevine ✓ |
169
- | Firefox | hls.js | Widevine ✓ |
170
- | Safari (macOS, iOS 17.1+) | hls.js (via MMS) | FairPlay ✓ (`com.apple.fps`) |
171
- | Older Safari / iOS | native HLS (fallback) | FairPlay — OS passthrough only |
172
- | Chrome/Firefox/Edge **on iOS** | hls.js | probe with `detectDrmSupport` (no Widevine on iOS) |
173
-
174
- Requires a browser with Media Source Extensions (or ManagedMediaSource) and
175
- Encrypted Media Extensions (all evergreen browsers).
176
-
177
- ---
178
-
179
- ## Mode A — Managed player
180
-
181
- The SDK owns the `<video>` element, bundles hls.js, and wires LL‑HLS + DRM
182
- automatically. It also handles live‑pickup retries, buffering recovery, stats, and
183
- silent DRM license refresh for long sessions.
184
-
185
- ### `createPlayer`
186
-
187
- ```ts
188
- function createPlayer(opts: CreatePlayerOptions): Promise<Player>;
189
- ```
190
-
191
- Resolves to a [`Player`](#player) as soon as the stream is attached (or armed, when
192
- `waitForLive` is set and the match is still upcoming). Terminal errors during the
193
- initial resolution (e.g. `NOT_FOUND`, `GONE`, `UNAUTHORIZED`) reject the promise; the
194
- live wait itself never blocks the promise and is surfaced through `'waiting'` events.
195
-
196
- ```ts
197
- const player = await createPlayer({
198
- video: document.querySelector('video')!,
199
- baseUrl: 'https://streams.oddin.gg',
200
- matchUrn: 'od:match:1234',
201
- credential: { apiKey: 'pk_live_…' },
202
- autoplay: true,
203
- muted: true,
204
- waitForLive: true,
205
- });
206
-
207
- player.on('statechange', (state) => console.log(state));
208
- player.on('waiting', (w) => console.log(`live in ~${Math.round(w.retryInMs / 1000)}s`));
209
- player.on('stats', (s) => console.log(s.droppedFrames, s.latencySeconds));
210
- player.on('error', (e) => console.error(e.code, e.httpStatus, e.message));
211
- ```
212
-
213
- #### `CreatePlayerOptions`
214
-
215
- | Option | Type | Default | Description |
216
- | --------------------- | --------------------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
217
- | `video` | `HTMLVideoElement` | — | **Required.** The element the SDK will control. |
218
- | `baseUrl` | `string` | — | **Required.** API base URL, e.g. `https://streams.oddin.gg`. |
219
- | `matchUrn` | `string` | — | **Required.** The match to play, e.g. `od:match:1234`. |
220
- | `credential` | [`CredentialSource`](#credentialsource) | — | **Required.** Your api‑key (or a function returning one). |
221
- | `autoplay` | `boolean` | `true` | Start playback once ready. |
222
- | `muted` | `boolean` | `false` | Mute the element. Set `true` for reliable autoplay under browser sound policies. |
223
- | `controls` | `'custom' \| 'native' \| 'none'` | `'custom'` | Which controls to render. See [Controls & theming](#controls--theming). |
224
- | `theme` | [`Partial<HavikTheme>`](#haviktheme) | Oddin brand | Re-skin the custom control bar (ignored unless `controls: 'custom'`). See [Controls & theming](#controls--theming). |
225
- | `statusOverlays` | `boolean` | `true` | Branded 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'`. |
226
- | `endedMessage` | `string` | "This stream has ended" | Message on the end-of-stream card. |
227
- | `errorMessage` | `string` | the error's message | Message on the fatal-error card (otherwise the error's own message). |
228
- | `waitForLive` | [`WaitForLive`](#waitforlive) | — | Arm on an upcoming match and auto‑attach at go‑live. |
229
- | `lowLatency` | `'auto' \| boolean` | `'auto'` | `'auto'` lets the player decide from the manifest. |
230
- | `engine` | `'auto' \| 'hls' \| 'native'` | `'auto'` | `'auto'` prefers hls.js wherever it is supported — including modern Safari/iOS via ManagedMediaSource — and falls back to native HLS otherwise. |
231
- | `userId` | `string` | — | Optional viewer id (sent as `X-User-Id` on license requests). |
232
- | `debug` | `boolean` | `false` | Turn 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. |
233
- | `hlsConfig` | `Partial<HlsConfig>` | — | Escape hatch for advanced hls.js tuning. |
234
- | `statsIntervalMs` | `number` | `2000` | How often `'stats'` is emitted. |
235
- | `licenseRefreshMs` | `number` | `480000` (8 min) | Silent DRM license‑URL refresh interval for long sessions. `0` disables. |
236
- | `poster` | `string` | — | Poster image shown before playback starts. |
237
- | `startLevel` | `number` | `-1` | Initial 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](#low-latency--adaptive-bitrate). |
238
- | `maxBitrate` | `number` | — | Cap ABR to renditions at/below this bitrate (bps). |
239
- | `liveLatencyTarget` | `number` | `2` | Target live‑edge latency in seconds (hls.js `liveSyncDuration`). The player derives a matching latency **ceiling** internally and catches up at 1.5×, so this is the only live‑latency knob you need. Lower = closer to live but more rebuffer‑prone. Live/LL only. |
240
- | `snapToLiveOnRefocus` | `boolean` | `true` | Snap to the live edge when a backgrounded tab is refocused while far behind. Live/LL only. |
241
- | `liveStateEvents` | `boolean` | `true` | Use the push-based **live-state SSE** channel for go-live and end-of-stream (see [Live state](#live-state-sse)). Graceful: falls back to polling if the endpoint is unreachable. Set `false` to disable. |
242
- | `eventsBaseUrl` | `string` | derived | Override the SSE endpoint base. Default: `baseUrl` with the host prefixed by `events.` (e.g. `feed.<d>` → `events.<d>`). |
243
-
244
- ### Low‑latency & adaptive bitrate
245
-
246
- The player ships tuned defaults for Oddin's low‑latency HLS, so you normally
247
- don't need to set any of the live or ABR knobs:
248
-
249
- - **Live latency** — playback targets **~2 s** behind the live edge
250
- (`liveLatencyTarget` → hls.js `liveSyncDuration`). It deliberately sits back
251
- from the bleeding `PART‑HOLD‑BACK` edge, where the newest partial segments
252
- aren't reliably published yet; chasing that edge causes constant rebuffering.
253
- Set `liveLatencyTarget` lower for closer‑to‑live (more rebuffer‑prone) or
254
- higher for steadier playback. _Lowered from 3 s — see the migration note below._
255
- - **Drift ceiling** — after a stall, the player catches up at up to **1.5×** and,
256
- as a backstop, force‑seeks back toward the target once latency exceeds an
257
- internal **ceiling (~12 s, derived as `max(12, liveLatencyTarget + 9)`)**. This is what
258
- stops latency from snowballing to tens of seconds after buffering. The ceiling
259
- is internal and always kept above your `liveLatencyTarget`.
260
- - **Over‑seek clamp** — the drift ceiling's counterpart on the _near_ side. A seek
261
- that lands closer to live than `liveLatencyTarget` is pulled back onto it, so
262
- dragging the scrub bar to its far right means **"go live"** rather than landing
263
- on the bleeding edge — where latency reads under a second and playback stutters
264
- frame‑by‑frame on an empty forward buffer. hls.js can't recover from that state
265
- on its own (its live‑sync only ever corrects being _behind_), so the stutter
266
- would otherwise persist for the rest of the session. Live only — VOD seeks are
267
- untouched, and the clamp stands down while chasing is suspended on a stale
268
- playlist (there is no live edge left to protect at that point). On the custom
269
- control bar the bar's right end **is** the target, so the thumb reads full at
270
- the live edge. Bring‑your‑own‑player (Mode B) owns its own seek UI and needs
271
- the equivalent clamp itself.
272
- - **Audio‑hole bridge** — `maxBufferHole` is raised to **0.5 s** so the ~0.45 s
273
- audio "remainder" gap at each segment boundary is bridged as a sub‑perceptible
274
- hitch instead of a rebuffer.
275
- - **Start quality** — auto ABR seeds a **~1 Mbps** estimate so the first
276
- rendition is one a modest link can sustain (**~360p**) and then **ramps up**
277
- within a few seconds as measured bandwidth allows — rather than grabbing a high
278
- rung and rebuffering on a constrained link. This trades a slightly softer first
279
- ~2 s for a **stall‑free start** (the first‑seconds buffering fix). In addition,
280
- `capLevelToPlayerSize` bounds the whole session to the player's pixel box, so a
281
- small/embedded player won't fetch 1080p. Pin a fixed rung with `startLevel`,
282
- cap the top with `maxBitrate`, or raise the seed via
283
- `hlsConfig.abrEwmaDefaultEstimate` if you want a sharper (higher‑risk) start.
284
-
285
- All of these can be overridden through the [`hlsConfig`](#playeroptions) escape
286
- hatch (e.g. `maxLiveSyncPlaybackRate`), but the defaults are tuned for Oddin's
287
- streams and rarely need changing. Raw live‑sync overrides are normalized so they
288
- can't crash the player: if you pass the count‑based `liveSyncDurationCount` /
289
- `liveMaxLatencyDurationCount`, the seconds‑based defaults step aside (hls.js
290
- rejects mixing the two); if you set `liveSyncDuration` alone, a matching ceiling
291
- is derived above it.
292
-
293
- > **Migration note:** the default `liveLatencyTarget` **dropped from 3 s to 2 s**.
294
- > Nothing to change — the drift ceiling stays 12 s and the ABR reaction budgets
295
- > are derived from the target, so they tighten with it automatically. Expect
296
- > playback ~1 s closer to live. If you were relying on the old behaviour, pass
297
- > `liveLatencyTarget: 3` explicitly.
298
-
299
- > **Migration note:** `liveCatchUpRate` was **removed** as a public option — the
300
- > catch‑up rate (1.5×) is now managed internally alongside the drift ceiling. If
301
- > you set it before, drop it; reach for `hlsConfig.maxLiveSyncPlaybackRate` only
302
- > if you genuinely need to override the rate.
303
-
304
- ### `Player`
305
-
306
- ```ts
307
- interface Player {
308
- readonly state: PlayerState;
309
- readonly descriptor: StreamDescriptor | null;
310
- play(): Promise<void>;
311
- pause(): void;
312
- setMuted(muted: boolean): void;
313
- setVolume(volume: number): void; // 0..1 (clamped)
314
- getStats(): PlaybackStats;
315
- // Track & quality control (empty/no-op on the native engine, which does ABR itself):
316
- getQualityLevels(): QualityLevel[];
317
- getCurrentQuality(): number; // -1 = auto
318
- setQuality(index: number | 'auto'): void;
319
- setMaxBitrate(bitrate: number | null): void;
320
- getAudioTracks(): AudioTrackInfo[];
321
- setAudioTrack(id: number): void;
322
- getTextTracks(): TextTrackInfo[];
323
- setTextTrack(id: number): void; // -1 = disable captions
324
- seekToLive(): void;
325
- enterPictureInPicture(): Promise<void>;
326
- exitPictureInPicture(): Promise<void>;
327
- retry(): Promise<void>; // recover from an error (re-resolve + re-attach)
328
- reload(): Promise<void>; // re‑resolve playback (refreshes the license URL) + re‑attach
329
- on<E extends PlayerEvent>(event: E, cb: (payload: PlayerEventMap[E]) => void): () => void;
330
- destroy(): void;
331
- }
332
- ```
333
-
334
- `on(...)` returns an **unsubscribe** function. Call `destroy()` to tear down hls.js,
335
- detach and clear listeners, and release the media element; the player is inert
336
- afterward (`play`/`pause`/etc. become no-ops).
337
-
338
- Notes:
339
-
340
- - `reload()` **rejects** (and emits `error`, setting state to `error`) if the
341
- re-resolution fails — `await` it or attach a `.catch`.
342
- - `play()` resolves even when the browser blocks autoplay; rely on the `playing`
343
- state / `error` event (not `play()`'s return value) to determine the outcome.
344
-
345
- <a id="playereventmap"></a>
346
-
347
- ### Player events
348
-
349
- `on(event, cb)` — the payload type depends on the event ([`PlayerEventMap`](#playereventmap)):
350
-
351
- | Event | Payload | Fires when |
352
- | ------------------ | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
353
- | `ready` | `void` | The manifest is parsed and the player is attached. |
354
- | `waiting` | [`WaitState`](#waitstate) | Armed 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). |
355
- | `playing` | `void` | Playback is progressing. |
356
- | `buffering` | `void` | The player is rebuffering. |
357
- | `paused` | `void` | Playback is paused. |
358
- | `ended` | `void` | The live stream ended. Playback is stopped and the last frame is kept. |
359
- | `error` | [`PlaybackError`](#playbackerror) | A fatal error occurred (playback stopped). |
360
- | `warning` | [`PlaybackError`](#playbackerror) | A non-fatal condition (e.g. FairPlay passthrough, a failed license refresh). Playback continues. |
361
- | `autoplayblocked` | `void` | The browser blocked autoplay (`NotAllowedError`). Show a tap-to-play / tap-to-unmute affordance, then call `player.play()` from the gesture. |
362
- | `qualitychange` | `number` | Active rendition changed (level index, `-1` = auto). |
363
- | `audiotrackchange` | `number` | Active audio track changed (track id). |
364
- | `texttrackchange` | `number` | Active text track changed (track id, `-1` = off). |
365
- | `pipchange` | `boolean` | Picture-in-Picture entered (`true`) or exited (`false`). |
366
- | `stats` | [`PlaybackStats`](#playbackstats) | Periodic stats sample (`statsIntervalMs`). |
367
- | `statechange` | [`PlayerState`](#playerstate) | Any state transition. |
368
-
369
- <a id="controls--theming"></a>
370
-
371
- ### Controls & theming
372
-
373
- The managed player ships a built-in, fully **skinnable** control bar. By default
374
- (`controls: 'custom'`) it wraps your `<video>` in a `.havik-player` container and
375
- renders the Oddin-branded UI: a center play/overlay, a seek bar, play/pause,
376
- volume, a live badge + go-live, quality / audio / subtitle menus,
377
- Picture-in-Picture, fullscreen, a buffering spinner, and **branded status cards**
378
- for the stopped/pre-play states — _ended_ ("This stream has ended"), _fatal
379
- error_ (message + Retry when retryable), _pre-play_ (poster + play CTA), and
380
- _armed-waiting_ ("Starting soon…") — so a finished or failed stream never leaves
381
- a frozen frame behind a dead play button. The cards pick up `theme.logoUrl` and
382
- the theme colors; customise the copy with `endedMessage`/`errorMessage`, or set
383
- `statusOverlays: false` to drive your own end/error UI from the player events.
384
- It auto-hides during playback, supports keyboard shortcuts (space/`k` play-pause,
385
- `m` mute, `f` fullscreen, `c` captions, `l` go-live, arrows seek/volume), and is
386
- fully keyboard- and screen-reader-accessible.
387
-
388
- ```ts
389
- type Controls = 'custom' | 'native' | 'none';
390
- ```
391
-
392
- | Value | Behaviour |
393
- | ---------- | ----------------------------------------------------------------------------------- |
394
- | `'custom'` | **Default.** The branded, themeable Havik control bar. |
395
- | `'native'` | The browser's built-in `<video controls>` UI. No wrapper element is added. |
396
- | `'none'` | No controls. Drive the player entirely through its [API](#player) (build your own). |
397
-
398
- Re-skin the custom bar in one of two ways — both set the same CSS variables, so
399
- they're interchangeable:
400
-
401
- **1. Pass a `theme`** (merged over the Oddin defaults; omitted keys keep the brand value):
402
-
403
- ```ts
404
- await createPlayer({
405
- video,
406
- baseUrl,
407
- matchUrn,
408
- credential: { apiKey },
409
- theme: {
410
- accent: '#14b8a6', // play button, seek fill, live dot, focus ring
411
- accentText: '#04201c', // text/icon sitting on the accent
412
- surface: '#0f172a', // control-bar + menu background
413
- logoUrl: 'https://cdn.example.com/logo.svg', // optional corner watermark
414
- },
415
- });
416
- ```
417
-
418
- **2. Or override the CSS variables** in your own stylesheet (handy for theming many
419
- players, dark/light switching, or matching an existing design system):
420
-
421
- ```css
422
- .havik-player {
423
- --havik-accent: #14b8a6;
424
- --havik-accent-text: #04201c;
425
- --havik-surface: #0f172a;
426
- --havik-radius: 4px;
427
- }
428
- ```
429
-
430
- <a id="haviktheme"></a>
431
-
432
- #### `HavikTheme`
433
-
434
- Each `theme` key maps to a `--havik-*` CSS variable on the `.havik-player` element:
435
-
436
- | `HavikTheme` key | CSS variable | Default (Oddin) | Used for |
437
- | ---------------- | ----------------------- | -------------------------- | --------------------------------------- |
438
- | `accent` | `--havik-accent` | `#E1B600` (gold) | Play button, seek fill, live dot, focus |
439
- | `accentText` | `--havik-accent-text` | `#1B1C23` (navy) | Text/icon on the accent |
440
- | `background` | `--havik-bg` | `#0e0f13` | Letterbox / behind-video background |
441
- | `surface` | `--havik-surface` | `#1B1C23` | Control-bar + menu surface |
442
- | `surfaceMuted` | `--havik-surface-muted` | `#2a2c36` | Hover / active surface |
443
- | `text` | `--havik-text` | `#ffffff` | Primary text / icons |
444
- | `textMuted` | `--havik-text-muted` | `#9aa0ad` | Secondary text (timestamps, inactive) |
445
- | `border` | `--havik-border` | `rgba(255, 255, 255, 0.1)` | Hairline borders |
446
- | `radius` | `--havik-radius` | `8px` | Corner radius for buttons / menus |
447
- | `fontFamily` | `--havik-font` | system UI stack | Control-bar font |
448
- | `logoUrl` | `--havik-logo` | — (none) | Optional corner watermark (a URL) |
449
-
450
- The default theme (`ODDIN_THEME`) and the `applyTheme(root, theme?)` helper are
451
- exported from the package root if you need the values directly or want to skin a
452
- container yourself:
453
-
454
- ```ts
455
- import { applyTheme, ODDIN_THEME, type HavikTheme } from '@oddin-gg/havik-player';
456
-
457
- applyTheme(myElement, { accent: '#14b8a6' }); // writes --havik-* vars
458
- ```
459
-
460
- ### `PlayerState`
461
-
462
- ```ts
463
- type PlayerState =
464
- 'idle' | 'waiting' | 'loading' | 'playing' | 'buffering' | 'paused' | 'ended' | 'error';
465
- ```
466
-
467
- ---
468
-
469
- ## Mode B — Bring your own player
470
-
471
- The SDK resolves the stream and gives you DRM helpers; you own the `<video>` element
472
- and the playback engine.
473
-
474
- ### `resolveStream`
475
-
476
- ```ts
477
- function resolveStream(opts: ResolveOptions): Promise<StreamDescriptor>;
478
- ```
479
-
480
- Resolves a match into a [`StreamDescriptor`](#streamdescriptor). With `waitForLive`, it
481
- polls (server‑paced) until the stream is live, then resolves.
482
-
483
- ```ts
484
- const credential = { apiKey: 'pk_live_…' };
485
- const stream = await resolveStream({
486
- baseUrl: 'https://streams.oddin.gg',
487
- matchUrn: 'od:match:1234',
488
- credential,
489
- waitForLive: true,
490
- });
491
- // stream.manifestUrl, stream.drmEnabled, stream.drm?.widevine?.licenseUrl, …
492
- ```
493
-
494
- #### `ResolveOptions`
495
-
496
- | Option | Type | Default | Description |
497
- | ------------- | --------------------------------------- | ------- | ------------------------------------------ |
498
- | `baseUrl` | `string` | — | **Required.** API base URL. |
499
- | `matchUrn` | `string` | — | **Required.** The match to resolve. |
500
- | `credential` | [`CredentialSource`](#credentialsource) | — | **Required.** |
501
- | `waitForLive` | [`WaitForLive`](#waitforlive) | — | Poll until live before resolving. |
502
- | `signal` | `AbortSignal` | — | Cancel the resolution (and any live wait). |
503
-
504
- ### `licenseRequestHeaders`
505
-
506
- ```ts
507
- function licenseRequestHeaders(
508
- descriptor: StreamDescriptor,
509
- credential: Credential,
510
- opts?: LicenseHeaderOptions,
511
- ): Record<string, string>;
512
- ```
513
-
514
- Returns the headers your player must attach to the DRM **license POST**:
515
-
516
- ```
517
- x-api-key: <your api-key> // same key used to resolve playback
518
- X-Match-Urn: <descriptor.matchUrn>
519
- X-Device-Id: <persistent device id>
520
- Content-Type: application/octet-stream
521
- X-User-Id: <opts.userId> // only when provided
522
- ```
523
-
524
- The license URL itself (`descriptor.drm.widevine.licenseUrl`) must be POSTed
525
- **verbatim** with the raw EME challenge bytes as the body. `LicenseHeaderOptions`:
526
-
527
- | Option | Type | Description |
528
- | ---------- | -------- | -------------------------------------------------------------------------------- |
529
- | `deviceId` | `string` | Override the persistent device id (defaults to [`getDeviceId()`](#getdeviceid)). |
530
- | `userId` | `string` | Forwarded as `X-User-Id`. |
531
-
532
- #### Example: wiring into hls.js yourself
533
-
534
- ```ts
535
- import Hls from 'hls.js';
536
- import { resolveStream, licenseRequestHeaders } from '@oddin-gg/havik-player';
537
-
538
- const credential = { apiKey: 'pk_live_…' };
539
- const stream = await resolveStream({ baseUrl, matchUrn, credential, waitForLive: true });
540
- const headers = licenseRequestHeaders(stream, credential);
541
-
542
- const hls = new Hls({
543
- emeEnabled: stream.drmEnabled && !!stream.drm?.widevine,
544
- drmSystems: stream.drm?.widevine
545
- ? { 'com.widevine.alpha': { licenseUrl: stream.drm.widevine.licenseUrl } }
546
- : undefined,
547
- drmSystemOptions: {
548
- videoRobustness: 'SW_SECURE_DECODE',
549
- audioRobustness: 'SW_SECURE_CRYPTO',
550
- videoEncryptionScheme: 'cbcs',
551
- audioEncryptionScheme: 'cbcs',
552
- },
553
- // EME license requests route through licenseXhrSetup (NOT xhrSetup):
554
- licenseXhrSetup: (xhr) => {
555
- for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);
556
- },
557
- lowLatencyMode: true,
558
- });
559
- hls.loadSource(stream.manifestUrl);
560
- hls.attachMedia(videoElement);
561
- ```
562
-
563
- <a id="detectdrmsupport"></a>
564
-
565
- ### `detectDrmSupport`
566
-
567
- ```ts
568
- function detectDrmSupport(opts?: {
569
- systems?: DrmSystem[]; // default: ['widevine', 'fairplay'], probed in order
570
- timeoutMs?: number; // OVERALL budget for the whole call, default 5000
571
- }): Promise<DrmSupportResult>;
572
-
573
- interface DrmSupportResult {
574
- verdict: 'supported' | 'no-cdm' | 'insecure-context' | 'blocked-by-policy' | 'probe-timeout';
575
- system?: DrmSystem; // first working system, when supported
576
- detail: Partial<Record<DrmSystem, string>>; // per-system outcome, for support bundles
577
- }
578
- ```
579
-
580
- Answers "can protected playback work in this browser at all?" so you can show
581
- an accurate message instead of a black player. It probes
582
- `requestMediaKeySystemAccess` **and** `createMediaKeys()` per system (access
583
- alone is not proof), with configs matching what the engine will actually
584
- request, bounded by a timeout. It never rejects.
585
-
586
- Rules of use:
587
-
588
- - **Call it lazily, cache the verdict yourself** — only once you know the
589
- content is DRM‑protected (`descriptor.drmEnabled`). The EME spec allows the
590
- probe to trigger consent prompts or CDM downloads, and results are not
591
- memoized; never run it on page load, and never probe for a clear stream.
592
- - **Probe, don't UA‑sniff.** The verdict is the playability gate; use the UA
593
- only to word the message.
594
- - `insecure-context` means EME is unavailable by spec — typical when testing
595
- over `http://<LAN‑IP>`; `localhost` is fine.
596
- - `blocked-by-policy` means an embedding problem (an iframe missing
597
- `allow="encrypted-media"`), not an unsupported browser — surface it to the
598
- integrator, not the viewer.
599
- - `supported` is necessary, not sufficient: licensing, CORS onboarding and
600
- packaging still apply.
601
-
602
- <a id="getdeviceid"></a>
603
-
604
- ### `getDeviceId` / `clearDeviceId`
605
-
606
- ```ts
607
- function getDeviceId(): string;
608
- function clearDeviceId(): void;
609
- ```
610
-
611
- `getDeviceId()` returns a persistent per‑device id (a random UUID stored in
612
- `localStorage`, regenerated only if storage is unavailable). It is sent as
613
- `X-Device-Id` on every DRM license request.
614
-
615
- > **Privacy:** the device id is a stable, cross‑session identifier (personal data
616
- > under GDPR/ePrivacy). Disclose it in your privacy policy and offer a reset —
617
- > `clearDeviceId()` removes the stored id so the next call generates a fresh one.
618
-
619
- ### `fetchCatalog`
620
-
621
- ```ts
622
- function fetchCatalog(opts: FetchCatalogOptions): Promise<Catalog>;
623
- ```
624
-
625
- Fetches the metadata catalog (tournaments → matches). **No** manifest or DRM data is
626
- included — use [`resolveStream`](#resolvestream) for playback. Supports a conditional
627
- refresh via ETag.
628
-
629
- ```ts
630
- const catalog = await fetchCatalog({ baseUrl, credential, status: ['live', 'upcoming'] });
631
- // poll cheaply later with the previous etag:
632
- const next = await fetchCatalog({ baseUrl, credential, etag: catalog.etag });
633
- if (next.notModified) {
634
- /* nothing changed */
635
- }
636
- ```
637
-
638
- `flattenMatches(catalog)` returns all matches as a flat [`CatalogMatch[]`](#catalogmatch).
639
-
640
- #### `FetchCatalogOptions`
641
-
642
- | Option | Type | Description |
643
- | ------------ | --------------------------------------- | -------------------------------------------------------------- |
644
- | `baseUrl` | `string` | **Required.** |
645
- | `credential` | [`CredentialSource`](#credentialsource) | **Required.** |
646
- | `signal` | `AbortSignal` | Cancel the request. |
647
- | `etag` | `string` | Prior ETag for a conditional GET (`notModified: true` on 304). |
648
- | `status` | `MatchLiveStatus \| MatchLiveStatus[]` | Filter by status. |
649
- | `sport` | `string` | Filter by sport. |
650
-
651
- ### `watchStatus`
652
-
653
- ```ts
654
- function watchStatus(opts: WatchStatusOptions): StatusWatcher;
655
- ```
656
-
657
- Polls a single match's live status and fires `onChange` on transitions (and once on
658
- first read). Returns a `StatusWatcher` with `stop()`. For a **push** channel (no
659
- polling) use [`subscribeLiveState`](#subscribelivestate) instead; `watchStatus` is the
660
- zero-dependency polling alternative when the SSE endpoint isn't available.
661
-
662
- ```ts
663
- const watcher = watchStatus({
664
- baseUrl,
665
- matchUrn,
666
- credential,
667
- onChange: (m) => {
668
- if (m.status === 'live') startPlayback();
669
- },
670
- });
671
- // later: watcher.stop();
672
- ```
673
-
674
- #### `WatchStatusOptions`
675
-
676
- | Option | Type | Default | Description |
677
- | ------------ | --------------------------------------- | ------- | ------------------------------------------ |
678
- | `baseUrl` | `string` | — | **Required.** |
679
- | `matchUrn` | `string` | — | **Required.** |
680
- | `credential` | [`CredentialSource`](#credentialsource) | — | **Required.** |
681
- | `onChange` | `(status: MatchStatus) => void` | — | **Required.** Fired on status transitions. |
682
- | `onError` | `(err: PlaybackError) => void` | — | Fired on a poll error; polling continues. |
683
- | `intervalMs` | `number` | `10000` | Poll interval (floored at `2000`). |
684
-
685
- <a id="live-state-sse"></a>
686
-
687
- ### `subscribeLiveState`
688
-
689
- ```ts
690
- function subscribeLiveState(opts: SubscribeLiveStateOptions): LiveStateSubscription;
691
- function deriveEventsBaseUrl(baseUrl: string): string | undefined;
692
- ```
693
-
694
- **Push**-based live state over Server-Sent Events (`events.<domain>/v1/events/{urn}`).
695
- The managed player uses this automatically (the `liveStateEvents` option) to go live
696
- the instant a match starts — without polling `/v1/playback` — and to detect
697
- end-of-stream instantly; BYO players can use it directly. `state` mirrors the
698
- `/v1/playback` outcome ladder:
699
-
700
- | `state` | meaning | maps to `/v1/playback` |
701
- | ---------- | ----------------------------- | ---------------------- |
702
- | `live` | serveable now — play | `200 OK` |
703
- | `upcoming` | scheduled, not serving yet | `425 Too Early` |
704
- | `ended` | was live; media stopped | `503` |
705
- | `gone` | ended past the catchup window | `410 Gone` |
706
-
707
- Uses `fetch` (not native `EventSource`, which can't set the `x-api-key` header),
708
- reconnects with backoff, and replays the current state on connect. Every event is
709
- also reported via `onAlive` (including heartbeats) so callers can treat the stream as
710
- healthy. A subscription problem is **non-fatal** — it retries in the background.
711
-
712
- ```ts
713
- import { subscribeLiveState, deriveEventsBaseUrl } from '@oddin-gg/havik-player';
714
-
715
- const sub = subscribeLiveState({
716
- eventsBaseUrl: deriveEventsBaseUrl(baseUrl)!, // e.g. https://events.<domain>
717
- matchUrn,
718
- credential,
719
- onState: (ev) => {
720
- if (ev.state === 'live') startPlayback(); // then resolveStream()/createPlayer()
721
- if (ev.state === 'ended' || ev.state === 'gone') stopPlayback();
722
- },
723
- });
724
- // later: sub.close();
725
- ```
726
-
727
- #### `SubscribeLiveStateOptions`
728
-
729
- | Option | Type | Default | Description |
730
- | --------------- | --------------------------------------- | ------- | ----------------------------------------------------------------- |
731
- | `eventsBaseUrl` | `string` | — | **Required.** SSE base, e.g. from `deriveEventsBaseUrl(baseUrl)`. |
732
- | `matchUrn` | `string` | — | **Required.** |
733
- | `credential` | [`CredentialSource`](#credentialsource) | — | **Required.** |
734
- | `onState` | `(ev: LiveStateEvent) => void` | — | **Required.** Initial snapshot on connect + every transition. |
735
- | `onError` | `(err: unknown) => void` | — | Non-fatal subscription error; the client keeps retrying. |
736
- | `onAlive` | `() => void` | — | Liveness tick on every received frame (incl. heartbeats). |
737
- | `minBackoffMs` | `number` | `1000` | Reconnect backoff floor. |
738
- | `maxBackoffMs` | `number` | `15000` | Reconnect backoff ceiling. |
739
-
740
- ### `isLowLatencyManifest`
741
-
742
- ```ts
743
- function isLowLatencyManifest(playlistText: string): boolean;
744
- ```
745
-
746
- Utility: returns `true` if an HLS playlist body contains low‑latency tags
747
- (`EXT-X-PART-INF` / `EXT-X-PART` / `EXT-X-PRELOAD-HINT`).
748
-
749
- ---
750
-
751
- ## Mode C — Iframe embed
752
-
753
- Embed a hosted player page and control it over `postMessage`. This is the lowest‑touch
754
- integration and isolates playback in its own browsing context.
755
-
756
- ### `mountEmbed`
757
-
758
- ```ts
759
- function mountEmbed(opts: MountEmbedOptions): EmbedHandle;
760
- ```
761
-
762
- Creates an iframe pointing at the hosted embed page, threads the configuration, and
763
- sets up an origin‑verified `postMessage` bridge.
764
-
765
- ```ts
766
- const embed = mountEmbed({
767
- container: document.querySelector('#player')!,
768
- src: 'https://player.oddin.gg/embed/',
769
- baseUrl: 'https://streams.oddin.gg',
770
- matchUrn: 'od:match:1234',
771
- onEvent: (msg) => console.log(msg),
772
- });
773
-
774
- embed.play();
775
- embed.setMuted(false);
776
- // embed.destroy();
777
- ```
778
-
779
- #### `MountEmbedOptions`
780
-
781
- | Option | Type | Description |
782
- | -------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
783
- | `container` | `HTMLElement` | **Required.** Element to mount the iframe into. |
784
- | `src` | `string` | **Required.** URL of the hosted embed page. |
785
- | `baseUrl` | `string` | **Required.** API base URL (threaded to the iframe). |
786
- | `matchUrn` | `string` | **Required.** Match to play. |
787
- | `apiKey` | `string` | **Dev only.** Appended as a query param. In production the embed page injects the key server‑side — omit this. |
788
- | `allowedFrameOrigin` | `string` | Origin of the embed page, used to verify its messages. Defaults to the origin of `src` (resolved against the current page when `src` is relative). |
789
- | `sandbox` | `string` | iframe `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"`. |
790
- | `muted` | `boolean` | Start muted. |
791
- | `onEvent` | `(msg: FrameToHost) => void` | Called for every event from the iframe. |
792
-
793
- #### `EmbedHandle`
794
-
795
- ```ts
796
- interface EmbedHandle {
797
- readonly iframe: HTMLIFrameElement;
798
- play(): void;
799
- pause(): void;
800
- setMuted(muted: boolean): void;
801
- setVolume(volume: number): void;
802
- setQuality(index: number): void; // -1 = auto
803
- setMaxBitrate(bitrate: number | null): void;
804
- setAudioTrack(id: number): void;
805
- setTextTrack(id: number): void; // -1 = off
806
- seekToLive(): void;
807
- enterPip(): void;
808
- exitPip(): void;
809
- retry(): void;
810
- load(matchUrn: string): void; // switch to a different match
811
- on(cb: (msg: FrameToHost) => void): () => void; // returns unsubscribe
812
- destroy(): void;
813
- }
814
- ```
815
-
816
- Track lists arrive from the iframe as an `oddin:tracks` event (see below); use those to
817
- build a quality/caption menu, then drive selection with `setQuality`/`setTextTrack`/etc.
818
-
819
- ### The embed page
820
-
821
- A ready‑to‑host page ships at `embed/index.html` (loads the CDN bundle and calls
822
- `bootEmbed()`). To self‑host, serve a page that runs:
823
-
824
- ```ts
825
- import { bootEmbed } from '@oddin-gg/havik-player';
826
- bootEmbed();
827
- ```
828
-
829
- `bootEmbed()` reads its [`EmbedConfig`](#embedconfig) from `window.HAVIK_EMBED_CONFIG`
830
- (server‑injected, preferred) or the URL query string, runs a managed player full‑bleed,
831
- and speaks the postMessage protocol. **The api‑key is never accepted over postMessage** —
832
- inject it server‑side in production.
833
-
834
- #### `EmbedConfig`
835
-
836
- Read by `bootEmbed()` in one of two **mutually-exclusive** modes: if
837
- `window.HAVIK_EMBED_CONFIG` is present (production) it is the **only** source — the
838
- query string is ignored entirely, so a tampered `?baseUrl=` can't redirect the injected
839
- api-key. Otherwise (dev/demo) config comes from the query string. The postMessage bridge
840
- **fails closed**: with no `parentOrigin`, the embed neither accepts commands nor posts
841
- events.
842
-
843
- | Field | Type | Default | Description |
844
- | -------------- | ----------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
845
- | `baseUrl` | `string` | — | **Required.** API base URL. |
846
- | `matchUrn` | `string` | — | **Required.** Match to play. |
847
- | `apiKey` | `string` | — | **Required.** Inject server‑side in production; query param is dev‑only. |
848
- | `parentOrigin` | `string` | — | 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. |
849
- | `autoplay` | `boolean` | `true` | Start playback once ready. |
850
- | `muted` | `boolean` | `true` | Start muted (recommended for autoplay). |
851
- | `waitForLive` | [`WaitForLive`](#waitforlive) | `true` | Arm and auto‑play at go‑live. |
852
-
853
- <a id="frametohost"></a>
854
- <a id="hosttoframe"></a>
855
- <a id="isoddinmessage"></a>
856
-
857
- ### postMessage protocol
858
-
859
- Every message is filtered with [`isOddinMessage`](#isoddinmessage) (anything not a
860
- recognized `oddin:` message is ignored). The **host** verifies `event.origin` against the
861
- embed page's origin on every message. The **iframe** verifies `event.origin` against its
862
- configured `parentOrigin` — `mountEmbed` always sets this, so the bridge is origin‑verified
863
- end‑to‑end. If you self‑host the embed page and call `bootEmbed()` directly, **always set
864
- `parentOrigin`** (see [`EmbedConfig`](#embedconfig)); without it the iframe accepts `oddin:`
865
- messages from any origin and posts events with target origin `*`.
866
-
867
- **Host → iframe** ([`HostToFrame`](#hosttoframe)):
868
-
869
- ```ts
870
- { type: 'oddin:play' } | { type: 'oddin:pause' }
871
- { type: 'oddin:setMuted'; muted: boolean } | { type: 'oddin:setVolume'; volume: number }
872
- { type: 'oddin:setQuality'; index: number } | { type: 'oddin:setMaxBitrate'; bitrate: number | null }
873
- { type: 'oddin:setAudioTrack'; id: number } | { type: 'oddin:setTextTrack'; id: number }
874
- { type: 'oddin:seekToLive' } | { type: 'oddin:enterPip' } | { type: 'oddin:exitPip' } | { type: 'oddin:retry' }
875
- { type: 'oddin:load'; matchUrn: string } | { type: 'oddin:destroy' }
876
- ```
877
-
878
- **Iframe → host** ([`FrameToHost`](#frametohost)):
879
-
880
- ```ts
881
- { type: 'oddin:ready'; protocol: number } // protocol = PROTOCOL_VERSION
882
- { type: 'oddin:autoplayblocked' }
883
- { type: 'oddin:state'; state: PlayerState }
884
- { type: 'oddin:waiting'; retryInMs: number; attempt: number; phase: string }
885
- { type: 'oddin:tracks'; quality: QualityLevel[]; audio: AudioTrackInfo[]; text: TextTrackInfo[] }
886
- { type: 'oddin:qualitychange'; index } | { type: 'oddin:audiotrackchange'; id } | { type: 'oddin:texttrackchange'; id }
887
- { type: 'oddin:stats'; droppedFrames; latencySeconds?; bandwidthKbps?; levelHeight?; lowLatency?; isLive?; atLiveEdge? }
888
- { type: 'oddin:error'; code: PlaybackErrorCode; message: string }
889
- ```
890
-
891
- The `oddin:ready` event carries the embed page's `protocol` version; `mountEmbed` warns on a
892
- mismatch with the host SDK (pin the embed page version to avoid CDN auto-update skew).
893
-
894
- If you handle messages directly (rather than via `EmbedHandle.on`), filter them with
895
- `isOddinMessage(event.data)` and always check `event.origin`.
896
-
897
- ---
898
-
899
- ## Reference
900
-
901
- <a id="playbackerror"></a>
902
-
903
- ### Errors
904
-
905
- Every API rejection is a typed **`PlaybackError`**:
906
-
907
- ```ts
908
- class PlaybackError extends Error {
909
- readonly code: PlaybackErrorCode;
910
- readonly httpStatus: number; // 0 for NETWORK / ABORTED; see the table for TIMEOUT
911
- readonly retryAfterMs?: number; // set for TOO_EARLY / RATE_LIMITED / UNAVAILABLE
912
- readonly liveStartsAtMs?: number; // epoch ms; set for TOO_EARLY when the server included `liveStartsAt`
913
- readonly requestId?: string; // server correlation id, when present
914
- }
915
- ```
916
-
917
- | `code` | HTTP | Meaning | Retryable |
918
- | -------------- | ------- | ---------------------------------------------------------------- | --------------------------- |
919
- | `INVALID_URN` | 400 | Malformed match URN. | No |
920
- | `NOT_FOUND` | 404 | Unknown match **or** not entitled (indistinguishable by design). | No |
921
- | `GONE` | 410 | Ended and past the catch‑up window. | No |
922
- | `TOO_EARLY` | 425 | Upcoming; not live yet. | Yes (via `waitForLive`) |
923
- | `UNAVAILABLE` | 503 | Should be live; origin warming up. | Yes |
924
- | `UNAUTHORIZED` | 401 | Bad/absent api‑key. | No |
925
- | `FORBIDDEN` | 403 | Origin not allowed, or DRM signature rejected. | No |
926
- | `RATE_LIMITED` | 429 | Per‑client request limit. | Back off |
927
- | `INTERNAL` | 5xx | Unexpected server/SDK error. | No |
928
- | `NETWORK` | 0 | The network request failed (offline, CORS, DNS). | Yes (in the live‑poll loop) |
929
- | `TIMEOUT` | (last)¹ | `waitForLive` exceeded `timeoutMs`. | No |
930
- | `ABORTED` | 0 | Cancelled via `AbortSignal`. | No |
931
-
932
- ¹ `TIMEOUT.httpStatus` carries the status of the last error it was waiting on — typically
933
- `425` while waiting for an upcoming match, `503` while an origin warms up, or `0` if the
934
- timeout lands on a network failure.
935
-
936
- ```ts
937
- import { PlaybackError } from '@oddin-gg/havik-player';
938
- try {
939
- await resolveStream({ baseUrl, matchUrn, credential });
940
- } catch (e) {
941
- if (e instanceof PlaybackError && e.code === 'NOT_FOUND') showUnavailable();
942
- }
943
- ```
944
-
945
- ### Data types
946
-
947
- #### `StreamDescriptor`
948
-
949
- The normalized playback credential.
950
-
951
- ```ts
952
- interface StreamDescriptor {
953
- matchUrn: string;
954
- protocol: 'hls';
955
- drmEnabled: boolean; // when false, no EME/CDM is needed
956
- manifestUrl: string; // unsigned HLS .m3u8
957
- drm?: DrmInfo; // present only when drmEnabled
958
- serverTime: string; // RFC3339
959
- liveStartsAt?: string; // present only while upcoming
960
- isLowLatency?: boolean; // filled by the player once detected
961
- }
962
- ```
963
-
964
- #### `DrmInfo`, `WidevineInfo`, `FairPlayInfo`, `DrmSystem`
965
-
966
- ```ts
967
- interface DrmInfo {
968
- widevine?: WidevineInfo;
969
- fairplay?: FairPlayInfo;
970
- }
971
- interface WidevineInfo {
972
- licenseUrl: string;
973
- } // pre-signed; POST verbatim
974
- interface FairPlayInfo {
975
- licenseUrl: string;
976
- certificateUrl: string;
977
- }
978
- type DrmSystem = 'widevine' | 'fairplay';
979
- ```
980
-
981
- <a id="credential"></a>
982
- <a id="credentialsource"></a>
983
-
984
- #### `Credential`, `CredentialSource`
985
-
986
- ```ts
987
- interface Credential {
988
- apiKey: string;
989
- }
990
- type CredentialSource = Credential | (() => Credential | Promise<Credential>);
991
- ```
992
-
993
- <a id="catalogmatch"></a>
994
-
995
- #### `Catalog`, `CatalogTournament`, `CatalogMatch`
996
-
997
- ```ts
998
- interface Catalog {
999
- tournaments: CatalogTournament[];
1000
- etag?: string;
1001
- notModified: boolean; // true on a 304 conditional refresh
1002
- }
1003
- interface CatalogTournament {
1004
- urn: string;
1005
- name: string;
1006
- sport: string;
1007
- isOffline: boolean;
1008
- matches: CatalogMatch[];
1009
- }
1010
- interface CatalogMatch {
1011
- matchUrn: string;
1012
- matchName: string;
1013
- status: MatchLiveStatus;
1014
- datePlannedStart?: string;
1015
- tournamentUrn: string;
1016
- tournamentName: string;
1017
- sport: string;
1018
- }
1019
- ```
1020
-
1021
- #### `MatchStatus`, `MatchLiveStatus`
1022
-
1023
- ```ts
1024
- type MatchLiveStatus = 'upcoming' | 'live' | 'ended';
1025
- interface MatchStatus {
1026
- matchUrn: string;
1027
- matchName?: string;
1028
- status: MatchLiveStatus;
1029
- datePlannedStart?: string;
1030
- }
1031
- ```
1032
-
1033
- #### `PlaybackStats`
1034
-
1035
- ```ts
1036
- interface PlaybackStats {
1037
- droppedFrames: number;
1038
- latencySeconds?: number; // live-edge latency (hls.js engine)
1039
- targetLatencySeconds?: number; // live-sync target latency; compare vs latencySeconds for drift
1040
- bandwidthKbps?: number; // estimated bandwidth (hls.js engine)
1041
- levelHeight?: number; // current rendition height
1042
- lowLatency?: boolean; // whether LL-HLS was detected in the manifest
1043
- isLive?: boolean; // current media playlist is live
1044
- atLiveEdge?: boolean; // playback is at/near the live edge
1045
- }
1046
- ```
1047
-
1048
- #### `QualityLevel`, `AudioTrackInfo`, `TextTrackInfo`
1049
-
1050
- ```ts
1051
- interface QualityLevel {
1052
- index: number;
1053
- width?: number;
1054
- height?: number;
1055
- bitrate: number;
1056
- codecs?: string;
1057
- }
1058
- interface AudioTrackInfo {
1059
- id: number;
1060
- name: string;
1061
- lang?: string;
1062
- default: boolean;
1063
- }
1064
- interface TextTrackInfo {
1065
- id: number;
1066
- name: string;
1067
- lang?: string;
1068
- }
1069
- ```
1070
-
1071
- <a id="live-pickup-options"></a>
1072
-
1073
- ### Live‑pickup options
1074
-
1075
- #### `WaitForLive`
1076
-
1077
- ```ts
1078
- type WaitForLive = boolean | WaitForLiveOptions;
1079
- ```
1080
-
1081
- Set to `true` for sensible defaults, or pass options:
1082
-
1083
- | Option | Type | Default | Description |
1084
- | --------------- | ---------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------- |
1085
- | `timeoutMs` | `number` | unbounded | Overall budget before giving up with `TIMEOUT`. |
1086
- | `floorMs` | `number` | `1000` | Minimum delay between polls (also the server minimum). |
1087
- | `ceilMs` | `number` | `30000` | Maximum delay between polls **inside the imminent window** (see `imminentMs`). Far-from-kickoff polls are widened — see below. |
1088
- | `kickoffAt` | `number \| string` | — | Scheduled kickoff (epoch ms or ISO string). When given, the SDK widens long-tail polls automatically — see "Far-future polling". |
1089
- | `imminentMs` | `number` | `600000` | Time-to-kickoff threshold for "imminent" (collapses to the tight `[floorMs, ceilMs]` band). |
1090
- | `sanityFloorMs` | `number` | `300000` | Hard cap on any single sleep (so an early go-live / schedule change is caught within bounded latency). 5 min default. |
1091
- | `jitter` | `boolean` | `true` | Add up to +15% jitter (never polls faster than the server asks). |
1092
- | `onState` | `(state: WaitState) => void` | — | Called before each wait. |
1093
-
1094
- ##### Far-future polling
1095
-
1096
- A viewer armed hours before kickoff would otherwise hammer `/v1/playback` every
1097
- 30s for the entire long tail. When **`kickoffAt`** is set (or the server includes
1098
- `liveStartsAt` on the 425 body — see [Errors](#errors) `liveStartsAtMs`), the
1099
- poll cadence is widened to `min(ttk / 10, sanityFloorMs)` for the long tail and
1100
- collapses to the tight `[floorMs, ceilMs]` range only inside the imminent
1101
- window. Guards baked in: the server's `Retry-After` is always a **floor** (the
1102
- server can tighten cadence near kickoff regardless), `sanityFloorMs` caps every
1103
- single sleep so an early go-live is caught within ≤5 min, and a `200` resolves
1104
- **immediately** at any point. Concretely, a match 2 h out now makes ≈30 polls
1105
- instead of ≈240.
1106
-
1107
- #### `WaitState`
1108
-
1109
- ```ts
1110
- interface WaitState {
1111
- phase: 'tooEarly' | 'unavailable' | 'rateLimited' | 'network';
1112
- retryInMs: number; // time until the next poll
1113
- attempt: number; // 1-based retry count
1114
- elapsedMs: number; // wall-clock since the wait started
1115
- ttkMs?: number; // time-to-kickoff used to compute this delay, if known
1116
- }
1117
- ```
1118
-
1119
- ### Advanced
1120
-
1121
- These exports are for advanced/custom integrations.
1122
-
1123
- - **`pollToLive(attempt, cfg, signal?)`** — the generic retry primitive behind
1124
- `waitForLive`. Polls an arbitrary `() => Promise<T>`, retrying on retryable
1125
- `PlaybackError`s and honoring `retryAfterMs`.
1126
- - **`isOddinMessage(data)`** — type guard for the postMessage protocol.
1127
- - **`ODDIN_THEME`** / **`applyTheme(root, theme?)`** — the default control-bar skin
1128
- and the helper that writes a [`HavikTheme`](#haviktheme) onto an element as
1129
- `--havik-*` CSS variables. See [Controls & theming](#controls--theming).
1130
-
1131
- > The internal engine seam (`PlaybackEngine` / `EngineEvent`) and one-shot helpers
1132
- > (`resolvePlaybackOnce`, `resolveCredential`) are **not** part of the public API and
1133
- > are excluded from the type declarations.
1134
-
1135
- ---
1136
-
1137
- ## Onboarding & CORS
1138
-
1139
- The api‑key is **publishable** — it is designed to live in browser JavaScript. Its
1140
- protection is a **server‑side allow‑list**, so every origin you serve the player from
1141
- must be onboarded before it will work:
1142
-
1143
- 1. The key's **allowed origins** must include each origin running the player (and, for
1144
- iframe embeds, the **parent page origins**).
1145
- 2. The DRM service's CORS allow‑list must include those same origins, or the
1146
- cross‑origin license request fails its preflight and DRM never starts.
1147
- 3. Scope the key's entitlements to the tournaments you serve.
1148
-
1149
- If you serve the player from a new domain, request it be added to the key's allow‑lists
1150
- first. Key revocation is not instantaneous (validation is cached for a few minutes).
1151
-
1152
- > **Never use a wildcard (`*`) origin allow‑list in production** — it removes the only
1153
- > guardrail on a publishable key.
1154
-
1155
- ### Service URL discovery
1156
-
1157
- Don't hard‑code `baseUrl` in your application. Serve it from your own backend, and
1158
- keep the backend current from the endpoint directory:
1159
-
1160
- ```http
1161
- GET https://status.oddin-video.gg/v1/endpoints.json
1162
- ```
1163
-
1164
- The document lists the current base URL per region and is served with
1165
- `Access-Control-Allow-Origin: *`, so any backend or build pipeline can consume it.
1166
- If an endpoint moves — most likely in regions with distinct internet regulations —
1167
- the directory updates and your backend follows, with no app release or store
1168
- re‑review. Endpoint changes and live availability for every Havik service are
1169
- published at [status.oddin-video.gg](https://status.oddin-video.gg).
1170
-
1171
- ---
1172
-
1173
- ## Troubleshooting
1174
-
1175
- | Symptom | Likely cause |
1176
- | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1177
- | `NETWORK` error on every call; preflight fails in devtools | Your origin isn't on the key's allowed‑origins / DRM CORS allow‑list. See [Onboarding](#onboarding--cors). |
1178
- | `UNAUTHORIZED` (401) | Wrong/expired api‑key, or wrong `baseUrl` environment (test vs prod key). |
1179
- | `FORBIDDEN` (403) on license requests | The 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. |
1180
- | `NOT_FOUND` (404) for a match you can see | The key isn't entitled to that tournament (404 is intentionally indistinguishable from "unknown"). |
1181
- | Player stays in `waiting` forever | The match hasn't gone live yet; the SDK is polling. Set `waitForLive.timeoutMs` to bound it. |
1182
- | Autoplay doesn't start | Browser sound policy — set `muted: true` for autoplay, or start playback from a user gesture. |
1183
- | Black video on Safari with DRM | Check 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. |
1184
- | Black video in Chrome/Firefox/Edge **on iOS** | iOS 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. |
1185
- | Black video, `levelHeight`/`droppedFrames` stuck | Check the browser console for an EME/CDM error and verify DRM CORS onboarding. |
1186
-
1187
- Include `PlaybackError.requestId` (when present) when contacting support — it correlates
1188
- to server‑side logs.
1189
-
1190
- ---
1191
-
1192
- ## Versioning & support
1193
-
1194
- - The package follows semantic versioning. Pin a version in production (npm and CDN).
1195
- - TypeScript definitions ship with the package; the types are the source of truth for
1196
- the API surface.
1197
- - The bundled hls.js version is managed by the SDK; do not assume a specific version in
1198
- managed mode.
1199
-
1200
- For onboarding (api‑keys, origin allow‑lists, entitlements) and support, contact Oddin.