Havik Player iOS SDK API Reference
HavikPlayer (Swift Package) · iOS player SDK for Oddin live streams (LL-HLS + FairPlay).
The native sibling of @oddin-gg/havik-player: same streams, same play sequence, same event and error vocabulary. iOS 15+.
Contents
- Overview
- Installation
- Concepts
- Mode A: Managed player
- Mode B: Bring your own AVPlayer
- Reference
- Versioning & support
Overview
The SDK plays Oddin live streams over Low-Latency HLS with FairPlay DRM, using AVPlayer + AVContentKeySession. One engine, no third-party playback stack. Two integration modes:
- Mode A (managed):
HavikPlayerowns anAVPlayerand wires live pickup, DRM, retries, stats, and end-of-stream detection automatically.HavikPlayerViewrenders it in SwiftUI. - Mode B (bring your own player):
HavikClient.resolveStream+ContentKeyCoordinator, attached to anAVPlayeryou own.
The iframe-embed mode of the web SDK has no iOS equivalent.
Installation
Install it with Swift Package Manager, as a binary package from the public oddin-gg/havik-ios-sdk repository. It needs iOS 15 or later and Xcode 26 or later, and no GitHub account or token.
In Xcode:
- File > Add Package Dependencies…
- Enter
https://github.com/oddin-gg/havik-ios-sdk. - Dependency rule: Up to Next Major Version, from
3.1.0. - Add the HavikPlayer library to your app target.
Or in Package.swift:
dependencies: [
.package(url: "https://github.com/oddin-gg/havik-ios-sdk", from: "3.1.0"),
],
targets: [
.target(name: "YourApp", dependencies: [
.product(name: "HavikPlayer", package: "havik-ios-sdk"),
]),
]The package ships debug symbols, so your crash reports show the SDK's frames by name, and a privacy manifest (PrivacyInfo.xcprivacy) that Xcode merges into your app's privacy report. CocoaPods isn't supported.
import HavikPlayerHavikPlayerSDK.version reports the SDK version at runtime.
Concepts
What you need
- A publishable api-key provisioned for your app. Your app's bundle id must be on the key's iOS-app allow-list (set at onboarding).
- A match URN (
od:match:…), from your Oddin integration or from the catalog API. - A physical device for DRM playback, because FairPlay does not run in the Simulator.
Authentication: attested sessions
Apps do not send the api-key on streams requests. Instead the SDK exchanges a platform attestation (Apple App Attest) for a short-lived session token via /v1/attest/*, and authenticates every catalog/playback/SSE request with that session, minting and refreshing transparently, including mid-match. The api-key itself is only used to mint sessions and on the DRM license surface.
let client = HavikClient(
environment: .integration,
apiKey: "pk_live_your_key",
attestation: HavikClient.defaultAttestation()
)HavikClient.defaultAttestation() picks AppAttestProvider on hardware that supports it and NoAttestationProvider otherwise (Simulator). Keys can be configured to require strict attestation, in which case the Simulator path is rejected by the server.
All authentication denials surface as the same opaque UNAUTHORIZED/FORBIDDEN errors by design; contact support with the requestId if you get stuck.
The play sequence
- Resolve.
GET /v1/playback/{urn}returns aStreamDescriptor: manifest URL, DRM configuration, server time. - Wait for live (optional). With
WaitForLive, the SDK polls politely (server-paced, jittered) until the match is live. - Play. The manifest goes to
AVPlayer; FairPlay keys are delivered throughAVContentKeySessionas the asset requests them. - Stay live. A pushed live-state channel (SSE) plus a manifest staleness watchdog detect end-of-stream; signed license URLs are re-resolved before they expire for long sessions.
DRM
FairPlay only. The descriptor carries the license and certificate URLs; the SDK handles the SPC/CKC exchange, certificate caching, the required X-Device-Id header, and re-resolving the descriptor when its signed license URL ages out. In Mode A this is invisible; in Mode B you attach a ContentKeyCoordinator to your asset.
Mode A: Managed player
HavikPlayer
let player = HavikPlayer(client: client, options: PlayerOptions(
matchUrn: "od:match:1234",
waitForLive: .default
))
player.start()| Member | Description |
|---|---|
init(client:options:) | Construct with a HavikClient and PlayerOptions. |
player: AVPlayer | The underlying AVPlayer; render it with HavikPlayerView or your own layer. |
events: AsyncStream<PlayerEvent> | Everything the player reports, delivered on the main actor. |
start() | Resolve (waiting for live if configured), attach DRM, begin playback. |
stop() | Tear down playback and subscriptions. Clears any terminal state. |
play() / pause() | Transport control. |
setMuted(_:) / setVolume(_:) | Audio control. |
setMaxBitrate(_:) | Cap ABR to renditions at or below this bitrate (nil = uncapped). |
qualityLevels: [QualityLevel] | The ladder, ascending by bitrate; empty until the item has loaded. |
currentQuality: Int | The selected level, or -1 for automatic. |
setQuality(_:) | Cap ABR at a level from qualityLevels (-1 = automatic). See below. |
audioTracks: [AudioTrackInfo] | The stream's audio renditions; empty until loaded, or with one muxed audio. |
setAudioTrack(_:) | Switch to a rendition from audioTracks (an unknown id is ignored). |
textTracks: [TextTrackInfo] | Subtitle and caption renditions, forced-only subtitles excluded. |
setTextTrack(_:) | Show a rendition from textTracks, or -1 to turn subtitles off. |
seekToLive() | Jump to the live edge. |
retry() | Recover from a failed state; re-resolves and restarts. |
reload() | Full re-resolve + restart while playing (e.g. after network change). |
isOffline: Bool | The device reports no network route. See Connection loss. |
Connection loss
The player watches the device's network path (NWPathMonitor). When the route is gone for a second (Wi-Fi off, airplane mode, no signal) it sets isOffline and sends .offline; playback carries on from the buffer while it lasts. When the route returns it sends .online and, if the session had failed by then, retries it as Retry would: a network error, or any failure with a retryable code that happened while offline. The terminal codes (gone, notFound, geoDenied, invalidUrn, unauthorized, drmDeviceRevoked, deviceUnsupported, attestationUnavailable) are never retried, and a player you stopped stays stopped.
A session the outage interrupted reloads at the live edge when the route returns: still buffering at that moment, or stopped by AVFoundation during the outage (it stops a live item after about 30 s offline without failing it). Resuming that stale item would play audio first, with the video seconds behind. A pause the viewer or your app made stays a pause.
The signal is trusted in one direction only: isOffline == false means "not known to be offline", since a captive portal still reports a route. A segment or playlist fetch that never got an answer is typed network, as is any item failure while offline.
Quality
AVPlayer can't pin a rendition, so setQuality(i) sets a ceiling: level i is the highest ABR may pick, and on a poor network it can still play a lower one. .qualityChanged reports the level actually on screen. setMaxBitrate still applies with a selection, and the lower of the two wins. Both persist across retry() and reload(); a level the reloaded ladder lacks means automatic. While a ceiling binds, PlaybackStats reports it as capReason == .bitrate with maxLevelHeight.
let levels = player.qualityLevels // [360p, 720p, 1080p]
player.setQuality(levels.count - 2) // at most 720p
player.setQuality(-1) // automatic againQualityLevel carries index, width, height, bitrate (the advertised peak, bits/sec) and codecs (avc1, hvc1). Variants with the same bitrate and height are one level, since a ceiling can't tell them apart.
Audio and text tracks
Tracks come from the playlist's EXT-X-MEDIA renditions once the item is ready. name is the playlist's NAME, as on the web, lang its LANGUAGE, and isDefault its DEFAULT. An id is the track's position in its list. Forced-only subtitles aren't listed, because they show by themselves when the audio needs them; while one is on screen, .textTrackChanged reports -1. The first change events after load report the starting selection, and later ones report every switch, whether from these calls, AVKit's own menu or automatic selection. A track chosen before the tracks have loaded is applied once they do.
PlayerOptions
| Option | Default | Description |
|---|---|---|
matchUrn | — | The match to play (required). |
autoplay | true | Start playback as soon as the item is ready. |
muted | false | Start muted. |
waitForLive | nil | Arm on an upcoming match; attach automatically at go-live. |
liveLatencyTarget | 2 s | Target distance from the live edge. A target AVPlayer honors when the manifest supports it, so measure glass-to-glass rather than assuming parity with the web SDK. |
snapToLiveOnForeground | true | Snap to live when the app foregrounds well behind the edge. |
maxBitrate | nil | Initial ABR cap, bits/sec. |
userId | nil | Optional viewer id, forwarded on the DRM license POST. |
statsInterval | 2 s | Cadence of .stats events. |
licenseRefreshInterval | 480 s | How stale a descriptor may get before its signed license URL is re-resolved. |
liveStateEvents | true | Subscribe to pushed live-state so end-of-stream is detected the instant it happens. |
rejoinOnLive | true | Rejoin automatically when an ended stream comes back live: the bridge recreated the session under a new manifest URL. Re-arms through wait-for-live (jittered up to 2 s). Needs liveStateEvents; gone is never rejoined. |
analyticsEnabled | true | Emit QoE beacons for the beacon plane only. Effective when the playback response carries an analytics sid and there is a beacons origin (the response's analytics.endpoint, else beaconsBaseURL); fire-and-forget, never affects playback. CMCD edge-log attribution is not governed by this switch; it follows the server-issued sid alone. |
analyticsIdleTimeout | 600 s | Close the QoE session as idle (END_REASON_IDLE) after this long paused, or after a suspension at least this long (never under 5 min). The next play reloads: a new session at the live edge. 0 disables. |
configuresAudioSession | true | Configure AVAudioSession for playback (audible with the ringer silenced). Set false if the host app owns the audio session. |
stuckReload | true | Reload a live playback whose playhead and buffer have both stood still for 8 s while it is trying to play, after the first frame, online and in the foreground. At most twice; 30 s of playing refunds it. Sends a .warning (UNAVAILABLE) and counts in PlaybackStats.stuckReloads. |
PlayerEvent
for await event in player.events {
switch event {
case .stateChanged(let state): …
case .stats(let stats): …
case .error(let error): …
default: break
}
}| Case | Meaning |
|---|---|
.ready | Item loaded and ready to play. |
.waiting(WaitState) | Armed on an upcoming match; payload describes the next poll. |
.playing / .buffering / .paused | Transport transitions. |
.ended(EndedReason?) | Stream over (pushed by SSE, the playlist's #EXT-X-ENDLIST, or the staleness watchdog), with the server's reason. A watchdog end while the push still says live reloads instead, with a .warning (UNAVAILABLE), at most twice per 10 minutes. An end with no reason (#EXT-X-ENDLIST or the watchdog) is emitted again with the server's reason when the push brings one. |
.error(PlaybackError) | Fatal; playback stopped. |
.warning(PlaybackError) | Non-fatal; playback continues (e.g. degraded live-state subscription). |
.pictureInPictureChanged(Bool) | PiP entered/exited, when shown with HavikPlayerView(havik:) or HavikVideoView. |
.stats(PlaybackStats) | Periodic health sample. |
.stateChanged(PlayerState) | Coarse state transition. |
.qualityChanged(Int) | The level on screen changed: an index into qualityLevels. |
.audioTrackChanged(Int) | The audio rendition changed: an id from audioTracks. |
.textTrackChanged(Int) | The text rendition changed: an id from textTracks, or -1 for off. |
.offline | The device lost its network route (isOffline is now true). |
.online | The route is back; a session that failed from the loss is retried. See Connection loss. |
PlayerState
idle · waiting · loading · playing · buffering · paused · ended · failed, mirroring the web SDK's PlayerState. failed is terminal until stop()/retry(). ended is too with rejoinOnLive: false; with it on (the default) the player leaves ended for waiting on its own when the stream comes back live, never after gone. buffering means the viewer is waiting for video: a stall AVFoundation reports while playback carries on doesn't enter it, and buffering ends once AVPlayer plays and the playhead moves on.
endedReason (an EndedReason?) says why an ended happened, and .ended carries the same value. interrupted means the match is still running and only its stream dropped (an ingest outage longer than the bridge's reconnect hold), so tell the viewer the match is still running, not that it ended. With rejoinOnLive (the default) the live-state subscription stays open after any end except gone, and when the stream comes back the player leaves ended for waiting and plays again on its own, so "reconnecting" is a promise it keeps. matchEnded is a real end, and nil means the server didn't say (an older server, or the staleness watchdog), so treat it as a real end. When an interruption turns out to be the end, the server says so and the player emits .ended once more with the new reason (matchEnded, or nil, which also means a real end). A late interrupted never downgrades a finished match, and gone is always matchEnded.
PlaybackStats
| Field | Description |
|---|---|
observedBitrate | Measured throughput, bits/sec. |
indicatedBitrate | Bitrate of the rendition being served, bits/sec. |
stallCount | Stalls since playback started. |
stuckReloads | Reloads of a frozen playback (stuckReload) for the life of the player. |
droppedFrameCount | Dropped frames this session, summed across rendition switches. |
bufferAhead | Seconds buffered ahead of the playhead. |
liveLatency | Distance from the live edge, seconds (nil until known). |
targetLatency, atLiveEdge | The latency the player aims for, and whether a live stream is within 1 s of it. |
isLive | Whether AVFoundation is playing the stream as live. |
levelHeight | Height of the rendition on screen, pixels. |
ladderHeights, ladderTopBitrate | The offered ladder (ascending heights) and its top bitrate. |
maxLevelHeight, capReason | The highest height ABR may pick and why (bitrate: your maxBitrate), only while that cap binds. |
renditionSwitches, upshifts, downshifts | ABR switches this session, and their direction. |
bytesLoaded, requestCount, requestErrors | Media bytes and requests this session, and error-log entries. |
videoCodec, audioCodec | Current rendition's codecs as AVFoundation reports them (avc1, hvc1; aac), not RFC 6381 strings. |
keySystem | fairPlay or none. |
cdnHost | Host of the most recent media request (host only). |
AVFoundation reports less than hls.js. There are no decoded-frame totals, low-latency flag, playlist bytes or per-request timings, so those web-SDK fields have no iOS counterpart.
HavikPlayerView (SwiftUI)
Wraps AVPlayerViewController: system transport controls, full-screen, AirPlay, and Picture-in-Picture come for free.
HavikPlayerView(havik: player)init(havik:showsPlaybackControls:allowsPictureInPicture:onPictureInPictureChange:onFullScreenChange:) or init(player:…) for a raw AVPlayer.
Fullscreen gotcha: AVKit's full-screen presentation covers the hosting SwiftUI view, firing its
onDisappear. Do not stop the player there. TrackonFullScreenChange/onPictureInPictureChangeand only stop when neither presentation is active, or the video blanks the moment fullscreen starts.
HavikVideoView (SwiftUI)
Renders the player into a plain AVPlayerLayer, with no system controls, for hosts that draw their own chrome. The SDK owns this view's Picture-in-Picture controller, so PiP can be started from code. That isn't possible with HavikPlayerView, because AVPlayerViewController has no public start or stop.
HavikVideoView(havik: player) // aspect-fit
Button("PiP") { player.enterPictureInPicture() }
.disabled(!canPiP) // your @State, refreshed from events
// in your event loop: case .ready, .stateChanged: canPiP = player.isPictureInPicturePossibleHavikPlayer isn't observable, so read isPictureInPicturePossible when a player event arrives. It turns true once an item is ready.
init(havik:videoGravity:startsPictureInPictureAutomatically:). The last parameter enters PiP when the app goes to the background while the view plays inline, which needs the app's "Audio, AirPlay, and Picture in Picture" background mode. Fullscreen is the host's layout: present the view full-bleed. Keep the view mounted while PiP shows; the system animates back to it when PiP stops.
When the stream ends, the player leaves this PiP. The PiP window can't show an end, and left open it would offer a play button over the last few buffered seconds. An interrupted end keeps it while rejoin is on, so a rejoin plays into the same window. After an end, a play from outside the SDK (the PiP window, Now Playing, media keys) is paused at once. HavikPlayerView's PiP is AVKit's own, and the SDK can't close it.
| Member | Description |
|---|---|
isPictureInPicturePossible | A HavikVideoView shows the player, the device has PiP, and an item is loaded. |
enterPictureInPicture() | Start PiP; a no-op unless possible. Reported by .pictureInPictureChanged(true). |
exitPictureInPicture() | Stop PiP; a no-op when it isn't active. A failure to start arrives as .warning. |
HavikStatusOverlay (SwiftUI)
Full-bleed status cards to lay over the video for the states where a frozen frame would mislead (html5's statusOverlays), and a spinner while the video loads or buffers. Nothing shows while it plays.
| State | Card |
|---|---|
.ended | "This stream has ended", or "Reconnecting — please stand by" if interrupted |
.failed | The error's message, with Retry unless re-resolving would fail again |
.waiting | "Starting soon…", or "Reconnecting — please stand by" after the viewer has played |
.idle / .paused | Before the first play only: a play button |
.loading / .buffering | No card: a spinner, after 0.4 s, so a short rebuffer doesn't flash it |
| Any other, while offline | "No internet connection — waiting to reconnect", no Retry (it resumes by itself) |
The offline card covers loading, playback, buffering, waiting and failed while isOffline is true, but never the ended card or the pre-play button.
A geo refusal names the viewer's country, and a revoked device gets "This device can't play protected video". A GONE failure (the match is over) shows the ended card, with HavikStatusMessages.ended, not an error. There's no Retry for GONE, NOT_FOUND, GEO_DENIED, INVALID_URN, UNAUTHORIZED, DRM_DEVICE_REVOKED, DEVICE_UNSUPPORTED or ATTESTATION_UNAVAILABLE. Override the copy with HavikStatusMessages. Its default interrupted message promises a reconnect, so pass your own when rejoinOnLive is off.
ZStack {
HavikPlayerView(havik: player, showsPlaybackControls: false)
HavikStatusOverlay(havik: player, logo: Image("brand"))
}HavikPlayer isn't observable, so show the overlay in a view your event loop re-renders on .stateChanged, .ended, .error, .offline and .online. The player now exposes lastError (the fatal error it stopped on) and hasPlayed.
Mode B: Bring your own AVPlayer
Resolving
let descriptor = try await client.resolveStream(
matchUrn: "od:match:1234",
waitForLive: .default
)
let asset = AVURLAsset(url: descriptor.manifestUrl)ContentKeyCoordinator
For DRM streams (descriptor.drmEnabled), create a coordinator and attach it before the asset starts loading:
let coordinator = ContentKeyCoordinator(client: client, descriptor: descriptor)
coordinator.attach(to: asset)
let item = AVPlayerItem(asset: asset)
// … your AVPlayer takes it from here. Keep `coordinator` alive!| Member | Description |
|---|---|
init(client:descriptor:userId:licenseRefreshInterval:) | userId rides the license POST; refresh interval defaults to 8 min. |
attach(to:) / detach(from:) | Register/unregister an AVURLAsset with the key session. Attach before loading. |
stop() | End the key session. |
events: AsyncStream<ContentKeyEvent> | Non-fatal notices: .keyDelivered(String), .failed(PlaybackError), .licenseURLRefreshed. |
Retain the coordinator for as long as the asset plays.
AVContentKeySessionholds its delegate weakly, so a coordinator that goes out of scope stops answering key requests, and playback stalls onwaitingForKeywith no error. Create one only whendrmEnabledis true.
LicenseRequest.headers(…) and LicenseRequest.Identity expose the exact license-request headers for hosts that need to observe or proxy the exchange.
Reference
HavikClient
Entry point for catalog discovery, playback resolution, and the live-state event stream. A Sendable value type: create once, pass anywhere.
| Initializer | Use |
|---|---|
init(baseURL:apiKey:attestation:appId:eventsBaseURL:beaconsBaseURL:apiHeaders:session:) | The sanctioned mode for apps: attested sessions (see Authentication). appId defaults to the main bundle id. |
init(baseURL:apiKey:eventsBaseURL:beaconsBaseURL:apiHeaders:session:) | Fixed-key mode. Works only against keys whose policy allows unattested callers. |
init(baseURL:credential:eventsBaseURL:beaconsBaseURL:apiHeaders:session:unauthorizedRecovery:) | Advanced: custom CredentialSource (e.g. your own token plumbing). |
init(environment:…), one per form above | Same, taking HavikEnvironment (.integration / .production) instead of a hand-written baseURL. Prefer these. |
environment:/baseURL: where the streams API is. Each initializer has anenvironment:twin takingHavikEnvironment(.integration→https://feed-dev.oddin-video.gg,.production→https://feed.oddin-video.gg). Prefer it: a hand-written base that is off thefeedhost convention breaks the derived events host (and the beacons host, against a server that names none) without any error.baseURLstays for a gateway in front of the API and isn't deprecated.eventsBaseURL: SSE endpoint; defaults to the base host prefixed withevents..beaconsBaseURL: QoE beacon ingest origin (see Analytics), used only when the playback response names none. Defaults to the platform hostname conventionfeed[-dev].<domain>→beacons[-dev].<domain>; when the convention doesn't apply and no override is given it isnil.apiHeaders: extra headers for every request tobaseURL(playback, catalog, match status, attest), for a gateway in front of the API that wants its own signal on top of the credential. They never go to the CDN, the DRM license or certificate endpoints, the events host, or the beacons origin. Additive only: an entry never replaces a header the SDK sets, andx-api-keyandX-Havik-Sessionare reserved (a session-authenticated request never gains an api key through the map).HavikClient.defaultAttestation(): App Attest on supporting hardware, app-binding only otherwise.
Catalog
let catalog = try await client.fetchCatalog(CatalogQuery(statuses: [.live]))| API | Returns |
|---|---|
fetchCatalog(_ query:) | Catalog: tournaments with nested matches. flattenedMatches for a flat list. |
fetchTournament(urn:) | One CatalogTournament. |
fetchMatch(urn:) | One CatalogMatch. |
CatalogQuery(sports:statuses:limit:) filters by sport and MatchLiveStatus (upcoming · pending · live · ended).
CatalogMatch.status is nil only when the server sent none. A value this SDK doesn't know yet maps to upcoming, and statusRaw keeps the server's string as sent. Persist statusRaw, since an unknown value re-encodes as upcoming.
In the catalog, pending means kickoff has passed and nothing serves right now. Either the stream is still being packaged, or it dropped mid-match.
CatalogMatch.teams lists the two sides, home first, as CatalogTeam (urn, name, isHome, logoUrl). It's nil when the server sent no usable team. logoUrl is set only for an absolute https URL, and a logo can still fail to load, so always render a fallback. fetchMatch(urn:) carries the same field: re-fetch a match to pick up a logo the server resolves late.
Live-state events (SSE)
for await event in client.liveStateEvents(matchUrn: urn) {
if case .state(let s) = event, s.state == .ended { … }
}liveStateEvents(matchUrn:minBackoff:maxBackoff:idleTimeout:notFoundRetry:) returns an AsyncStream<LiveStateStreamEvent>:
.state(LiveStateEvent): snapshot on connect, then every transition (live · upcoming · pending · ended · gone). A state this SDK doesn't know yet arrives asupcoming, with the server's string instateRaw. Onended,reasonisinterrupted,matchEnded, or nil (an older server, or a value this SDK doesn't know)..alive: liveness tick; the subscription is healthy..failure(PlaybackError): non-fatal; the client reconnects with backoff, except as below.
pending means kickoff has passed and the stream is being packaged. live follows within seconds to minutes. The managed player waits on it exactly as on upcoming. Both answer /v1/playback with 425, but only upcoming carries a liveStartsAt to count down to.
A connection that stops delivering without closing (a black-holed socket after a network change, a proxy half-close) would otherwise hang forever. After idleTimeout seconds with no byte (default 45, two missed server heartbeats), the request is cancelled, a .failure is emitted and the client reconnects with backoff. 0 disables the watchdog.
Two subscribe answers are special. A 410 (GONE: the match is gone for good) ends the subscription: the .failure carries it and the stream finishes. A 404 (NOT_FOUND: not in the catalog now, either ended and dropped or not listed yet) keeps retrying, but every notFoundRetry seconds (default 300, not capped by maxBackoff). So a finished match costs one request every five minutes instead of one every 15 s, and a match listed late is still picked up. The managed player emits one .warning with that code, naming the match and what the subscription does next. Playback isn't affected, and end-of-stream detection falls back to the manifest watchdog.
Cancel the consuming task to unsubscribe. The managed player consumes this internally when liveStateEvents is enabled.
Analytics: CMCD & QoE beacons
The SDK participates in two analytics planes, both keyed to the per-playback analytics sid: an opaque, non-secret UUID the playback response carries (StreamDescriptor.analytics) when the analytics plane is enabled server-side for the key. No sid → both planes silent. The sid grants nothing (DRM remains the access gate) and is memory-only, never written to disk or to any persistent store.
CMCD edge-log attribution: follows the sid alone. When the descriptor carries a sid, the manifest URL gains the CTA-5004 query-mode CMCD parameter (CMCD=sid%3D%22…%22). AVPlayer offers no per-request CMCD hook, so the sid rides the manifest request only, the same shape as the web SDK's Safari-native fallback. This plane is not governed by analyticsEnabled: it is the platform's edge-log attribution riding an existing request, and the per-customer switch lives server-side (the server includes or omits the sid).
QoE beacons: governed by analyticsEnabled. The managed player posts batched QoE beacons (session start/end, 15-second heartbeats, state transitions, errors) to {origin}/v1/beacons, one session per sid. The origin is the one the playback response names in analytics.endpoint (havik-streams v0.10.0+), else beaconsBaseURL. Attested clients stamp each batch with X-Havik-Session so ingest can attribute it to a verified client id; a credential failure costs the attribution, never the batch, and the api-key never rides the beacon path. Delivery is fire-and-forget: a lost batch is dropped, never retried, and never affects playback.
Startup (startupTimeMs, and the manifest and first-segment stages before it) is measured from play intent. With autoplay on that's when the session starts. With it off, it's the viewer's first play, from play() or AVKit's own play button, so time spent before pressing play isn't startup latency. A stage that finished before that play is recorded as 1 ms. On a FairPlay stream, SessionEnd also carries drmSetupMs: from the same start to the first content key delivered (certificate, SPC, licence). It also carries licenseTimeMs, the first licence round trip, whatever its outcome; renewals don't overwrite it. html5's firstPlaylistMs isn't sent, because AVPlayer doesn't report the media playlist load separately. Rebuffer counts and time are a delivery figure. Buffering that starts within 1 s of a playback jump is the jump's, not the network's, so it isn't counted. A jump is anything AVFoundation reports as one: seekToLive(), a scrub in AVKit's controls, or a jump the player makes on its own, such as falling out of the live window. Neither is a stall that starts while the viewer can't see the player (app in the background, not in Picture-in-Picture). Time accrues only while such a stall is visible, so the visible part of a stall the viewer returns to still counts.
Each heartbeat also carries the interval's rebuffer time and count, so a stall can be tied to the CDN host that served it. A stall that spans two heartbeats is split between them, and its count goes in the interval where it began. Heartbeats also carry the interval's active watch time: playing, visible and audible (not muted, volume above 0). SessionEnd carries the total as activeWatchTimeMs. Both are measured on the device. The per-interval figures add up to the session totals as of the last heartbeat; time after it appears in SessionEnd only.
SessionStart says where the session runs: device class, the hardware model identifier (such as iPhone17,1), OS version, screen size in points and its scale, the app's bundle id, and whether Low Data Mode is on, beside the connection. It never carries the device name, an advertising or vendor identifier, or an IP. Once the stream's ladder or codec is known, a MediaInfo beacon says what was negotiated: video and audio codec as AVFoundation names them (avc1, aac), FairPlay or none, the offered heights and top bitrate. It goes out again only if those change.
Heartbeats also carry the interval's up- and downshifts, media requests and request errors, hidden time and muted-while-playing time, plus the CDN host, the rendition height, the playback rate, whether playback is at the live edge, and, on a live stream, the drift from the latency target (positive when behind it). SessionEnd carries the hidden and muted totals. A rendition switch is a change of bitrate, the same count PlaybackStats reports. Request timing percentiles and decoded frames aren't sent, because AVFoundation doesn't report them per request.
Errors carry the pipeline stage they interrupted: resolve, manifest, DRM, first segment, segment or decode. A stage comes from where the failure was raised and how far the item had got. They also carry the CDN host serving at the time. State changes carry an inferred cause: a stall within 1 s of a jump is the seek's, otherwise the network's. A pause or resume is the viewer's, and a failure is an error. A session that never played reports the stage it failed at. When the app stops a session before its first frame, with no error, it ends as END_REASON_ABORTED rather than as a failure.
SessionEnd also carries engagement totals:
- time waiting for the match to go live;
- the playback delivered before the first stall;
- when playback first became audible (for a muted autoplay, the unmute);
- the position the viewer left at;
- how long after a stall or an error the viewer left, if within 30 s and the stream didn't end on its own;
- how many times the volume or mute changed;
- time in fullscreen and in Picture-in-Picture.
State changes also say which surface the viewer was on: inline, fullscreen or PiP, with PiP taking precedence. PiP is reported from both views. Fullscreen is reported from HavikPlayerView; with HavikVideoView, fullscreen is your layout, so it counts as inline.
The state a player starts in isn't a change.
A session paused longer than analyticsIdleTimeout (10 min by default) ends as END_REASON_IDLE. So does one whose app was suspended in the background at least that long, as of the last heartbeat before the suspension, so the suspended time isn't watch time. The viewer's next play then reloads: a new session at the live edge rather than a resume of one that has closed. An ended or failed player never reloads this way.
Beacons require all three: analyticsEnabled (default true), a sid in the playback response, and an origin: analytics.endpoint from the server, or a non-nil beaconsBaseURL. So a baseURL that isn't a feed host (your own gateway) still beacons against a v0.10.0+ server. Mode B (bring-your-own-player) has no beacon emitter, because beacons are a managed-player feature; the CMCD sid in Mode B is yours to attach (or not) when you build the asset URL.
WaitForLive
Live-pickup policy: how the SDK paces /v1/playback polls for an upcoming match. The cadence is tuned against the server's rate limiter; prefer the defaults.
| Field | Default | Description |
|---|---|---|
timeout | nil | Overall budget before failing with .timeout. Nil = unbounded. |
floor | 1 s | Minimum delay between polls. |
ceiling | 30 s | Maximum delay inside the imminent window. |
kickoffAt | nil | Scheduled kickoff; widens far-future polling. The SDK also reads the server's hint automatically. |
imminentWindow | 600 s | Window before kickoff where cadence tightens. |
sanityCeiling | 300 s | Absolute cap on any single wait. |
jitter | true | Up to +15% jitter so viewers do not poll in lockstep. |
WaitState (in .waiting events / onWait callbacks) reports the phase (tooEarly · unavailable · rateLimited · network) and delay of each wait.
Errors
Every failure is a PlaybackError:
| Field | Description |
|---|---|
code | PlaybackErrorCode (below). |
httpStatus | HTTP status, 0 when the failure never reached HTTP. |
message | Human-readable description. |
retryAfter | Server-requested backoff, when sent. |
requestId | Server request id; quote it to support. |
serverCode | Raw server error code. |
liveStartsAt | Scheduled kickoff, when a 425 body carried it. |
country | Viewer's country (alpha-2), set for geoDenied only. |
isWaitable | Whether the live-pickup loop would retry this code. |
PlaybackErrorCode (mirrors the web SDK, plus two native-only cases):
A geoDenied error means a retry would be refused again: tell the viewer the match isn't available in their country, naming country when it's set. A server without the 451 answers notFound for the same case. A drmDeviceRevoked error means the license server won't serve this device at all, so the match, the key and the network aren't the problem. A license 403 with any other body stays forbidden, and serverCode carries the body code (cdm_revoked, license_refused) either way. The managed player fails the match on both.
A drmClient error means the device's DRM delivery broke rather than a server refusing the viewer. A genuine license or certificate 401/403 stays unauthorized/forbidden, so branch on the code, not on httpStatus. A retry can recover a transient delivery failure; a device that can't play the stream fails the same way again.
| Code | HTTP | Meaning |
|---|---|---|
invalidUrn | 400 | Malformed match URN (terminal). |
notFound | 404 | Unknown URN or not entitled; deliberately indistinguishable (terminal). |
geoDenied | 451 | Booked for the key, not in the viewer's country; see country (terminal). |
gone | 410 | Ended past the catch-up window (terminal). |
tooEarly | 425 | Upcoming; retried per Retry-After. |
unavailable | 503 | Should-be-live but origin failing; retried with backoff. |
unauthorized | 401 | Bad/absent credential (terminal). |
forbidden | 403 | Surface not allowed / DRM entitlement refused (terminal). |
drmDeviceRevoked | 403 | License refused for this device's DRM client, body cdm_revoked (terminal). |
drmClient | (DRM) | Client-side DRM failure: no usable key system, a FairPlay error, or license/certificate delivery failing without a server denial; httpStatus carries the license or certificate status when there was one (retryable). |
rateLimited | 429 | Per-IP limiter; backs off per Retry-After. |
internalError | 5xx | Unexpected server error (terminal). |
network | — | Transport failure: no answer from the server, or a playback failure while offline. Retried while waiting for live, and automatically when the connection returns. |
timeout | — | Gave up waiting for live (terminal). |
aborted | — | Caller cancelled (terminal). |
attestationUnavailable | — | App Attest cannot run on this device (native-only). |
attestationFailed | — | The server rejected the attestation or app binding (native-only). |
Data types
StreamDescriptor: the /v1/playback result: matchUrn, manifestUrl, drmEnabled, drm (DrmInfo), serverTime, liveStartsAt, analytics (AnalyticsInfo), extensions, resolvedAt. fairPlay is a convenience accessor for drm?.fairplay gated on drmEnabled.
DrmInfo: widevine: WidevineInfo? (licenseUrl) and fairplay: FairPlayInfo? (licenseUrl, certificateUrl). License URLs are signed and short-lived (~10 min), and the SDK re-resolves before expiry. If a license POST still comes back 403 from the signature check (serverCode forbidden), for example after the device clock jumped or a signing key rotated, the coordinator re-resolves once and re-sends the same request on the new URL. A second refusal, and every other refusal (cdm_revoked, license_refused, entitlement_denied), fails as before.
AnalyticsInfo: sid: String?, the per-playback analytics identity, and endpoint: URL?, the beacons origin the server names. Present only when the analytics plane is enabled server-side; grants nothing and is never persisted. endpoint is kept only as a bare https origin (no path, query, fragment or userinfo), normalized to a lower-case host without a default port.
Credential: apiKey + optional sessionToken. CredentialSource: .fixed(Credential) or .dynamic(async provider).
MatchLiveStatus: upcoming · pending · live · ended (catalog vocabulary).
JSONValue: decoded form of the descriptor's open extensions map.
Attestation
| Type | Role |
|---|---|
AttestationProvider | Protocol: produce AttestationMaterial for a server challenge; handleDenial() may clear cached state and permit ONE retry. |
AppAttestProvider | Apple App Attest implementation (hardware-backed). |
NoAttestationProvider | App-binding only: Simulator/dev, non-strict keys. |
AttestationMaterial | type, attestation (base64 payload), keyId, isAttestation. |
Most apps never touch these directly; use HavikClient.defaultAttestation().
Device identity
HavikDeviceID.current: a stable per-device UUID stored in the Keychain (survives reinstalls; not identifierForVendor), sent as X-Device-Id on every license request. HavikDeviceID.reset() clears it, which is worth surfacing to viewers as a "reset my device identifier" control.
Versioning & support
Semantic versioning on v* tags; HavikPlayerSDK.version at runtime. The error-code and event vocabularies are shared with the web SDK so support runbooks apply across platforms. Questions: havik-support@oddin.gg.