Core

The types and functions in react-video-kit/core, for plugins and providers.

This entry has no React in it. Use it for types such as Player and MediaState, and for writing plugins and providers.

Functions

createClock

One shared loop for all time-driven writes. Each binding declares how far time must move before a write is visible, so a long video on a short track wakes rarely, and a paused player does no work at all.

() => OwnedClock
createPlayer

Builds a player. Pure: it touches no DOM until mount and attach.

(options?: PlayerOptions) => Player
createScope

Ownership for everything a lifecycle hook starts. Cleanups run in reverse order.

() => OwnedScope
definePlugin

Declares a plugin. Calling the result creates an instance for plugins, and the factory itself is the typed key for useVideoState and useCommands. create runs once for each player, so it can hold that player's private state.

<Name extends string, Options extends unknown[], State extends object = Record<never, never>, Commands extends object = Record<never, never>>(name: Name, create: (...options: Options) => PluginSpec<State, Commands>) => PluginFactory<Name, Options, State, Commands>
sourceKey

A stable identity for src, so re-rendering with equal values doesn't reload.

(input: SourceInput | null | undefined) => string
toLoadRequests

Expands any accepted src shape into the requests to try, in order.

(input: SourceInput | null | undefined) => LoadRequest[]

Types

AnyPlugin

A plugin instance with its types erased, as plugins accepts them.

FieldTypeDescription
namestringThe plugin's name, which must be unique within a player.
create() => PluginSpec<object, object>Builds the spec. Each player calls this, so an instance can be shared safely.
AnyPluginFactory
FieldTypeDescription
pluginNamestringThe name of the plugin this factory creates.
Capabilities
FieldTypeDescription
seekbooleanFalse where seeking isn't possible, such as a live stream with no window.
ratebooleanFalse where the rate can't change, such as on a Cast receiver.
volumebooleanFalse where the platform owns volume, such as iOS.
Clock
FieldTypeDescription
time() => numberCurrent playback position from the active provider. Doesn't allocate.
bind(write: (time: number, jumped: boolean) => void, resolution: () => number) => () => voidCalls write with the time whenever it has moved by at least resolution() seconds, plus once immediately and after every discontinuity, which jumped marks. Returns unbind.
sync() => voidWrites every binding now, for seeks, source changes, and provider swaps.
CommandsOf
CommandsOf<Factory>
CoreCommands
FieldTypeDescription
play() => Promise<boolean>Resolves to whether playback started. Never rejects.
pause() => voidPauses playback, unless a lock blocks it.
seek(time: number) => voidMoves to time in seconds, kept within the timeline.
scrub(active: boolean) => voidHolds playback while the viewer drags the timeline, then restores it.
setVolume(volume: number) => voidSets the volume, keeping it between 0 and 1.
setMuted(muted: boolean) => voidMutes or unmutes, leaving the volume as it is.
setRate(rate: number) => voidSets the playback speed, ignoring anything that isn't above 0.
setQuality(id: string | "auto") => voidSwitches to this level, or to automatic choice with auto if the provider offers it.
setAudioTrack(id: string) => voidSwitches to the audio track with this id.
setTextTrack(id: string | null) => voidTells the provider which text track to use, or none with null.
setSource(source: SourceInput | null) => voidChanges what plays, or clears it with null.
reload(startTime?: number) => voidLoads the current source again, optionally resuming from startTime. After a failure it picks up where that interrupted, and plays if the viewer was watching.
DeveloperErrorCode

The codes on errors thrown for a mistake in the code using the library.

DeveloperErrorCode
Gate
(request: Request, next: (request: Request) => void | Promise<void>, context: PluginContext<State>) => void | Promise<void>
Gates
FieldTypeDescription
load?((request: LoadRequest, next: (request: LoadRequest) => void | Promise<void>, context: PluginContext<State>) => void | Promise<void>)Runs before a source loads, and can change the request or hold it back.
play?((request: void, next: (request: void) => void | Promise<void>, context: PluginContext<State>) => void | Promise<void>)Runs when play is called, and can delay or decline it.
seek?((request: number, next: (request: number) => void | Promise<void>, context: PluginContext<State>) => void | Promise<void>)Runs before a seek, and can change the position or decline it.
KnownVideoErrorCode

Every code the library reports. react-video-kit/errors lists them with their details.

KnownVideoErrorCode
LiveState
FieldTypeDescription
dvrbooleanWhether the viewer can seek back through a window.
startnumberEarliest seekable position.
edgenumberLive edge.
latencynumberDistance the engine aims to keep from the edge, in seconds.
LoadRequest
FieldTypeDescription
sourceSourceObjectThe URL and type to load.
renditions?readonly Rendition[]All the files of this video, for providers that switch between them.
initialRendition?numberPosition in renditions of the file that source points to.
startTime?numberPosition to resume from, in seconds.
drm?unknownSet by the DRM plugin's load gate. Providers translate it for their engine.
LoadStrategy
LoadStrategy
Lock
FieldTypeDescription
idstringNames what holds the lock, such as ads.
commandsreadonly LockableCommand[]The commands blocked while the lock is held.
LockableCommand
LockableCommand
MediaErrorInfo
FieldTypeDescription
codeVideoErrorCodeSays what went wrong, in a form that stays the same between versions.
messagestringThe browser's or engine's own words, for logs. Viewers see translated text instead.
fatalbooleanTrue when the error stopped playback, false when it can carry on.
retryable?booleanTrue when trying again could work, which recovery and **Try again** go by. When it's left out, recovery doesn't retry and the overlay still offers **Try again**.
nativeCode?string | numberThe browser's or engine's own code, such as 3 from a MediaError or fragLoadError from hls.js.
cause?unknownThe original error object or event, for logs.
source?SourceObjectThe source that failed, when known.
MediaState

Everything the kernel knows about playback. Time is on the clock, not here.

FieldTypeDescription
statusMediaStatusThe load stage, from idle through loading to ready, or error after a fatal failure.
sourceSourceObject | nullThe source that was asked for. Switching rendition doesn't change it.
providerstring | nullThe name of the active provider, such as native or hls, or null before one loads.
pausedbooleanTrue while playback is paused, and left as it was during scrubbing.
endedbooleanTrue once playback has reached the end.
waitingbooleanTrue while playback has stalled, waiting for data.
seekingbooleanTrue while a seek is in progress.
scrubbingbooleanTrue while the viewer drags the timeline. paused keeps their intent meanwhile.
startedbooleanTrue once playback has begun for the current source.
durationnumberLength in seconds, which is 0 until known and Infinity for a stream with no end.
bufferedreadonly (readonly [number, number])[]The ranges downloaded so far, as start and end pairs in seconds.
volumenumberThe volume, from 0 to 1.
mutedbooleanTrue while the sound is muted.
ratenumberThe playback speed, where 1 is normal.
qualitiesreadonly QualityLevel[]The levels the provider offers.
quality{ mode: "auto" | "manual"; active: string | null; canAuto?: boolean; }The active level, and who chose it: the provider or the viewer.
audioTracksreadonly MediaTrackInfo[]The audio tracks to choose from.
audioTrackstring | nullThe id of the active audio track, or null when there is none.
textTracksreadonly MediaTrackInfo[]Text tracks as an engine names them, for those it adds to the video, whose own label it can't set. Empty when the video's list says all there is to know.
liveLiveState | nullDetails of the live stream, or null when the source isn't live.
timelineTimelineThe range the viewer can seek through, and what kind of content it covers.
capabilitiesCapabilitiesWhat the current provider or stream allows.
locksreadonly Lock[]The locks in force, which block commands until released.
errorMediaErrorInfo | nullThe latest error, cleared by the next load. Check fatal, since playback may be carrying on.
playRejectedstring | nullThe name of the error when the browser refused to start playback, usually autoplay policy.
MediaStatus
MediaStatus
MediaTrackInfo
FieldTypeDescription
idstringIdentifies the track to commands that select one.
label?stringName shown in menus.
language?stringLanguage tag, such as en.
kind?stringThe track's role as its source reports it, such as main or subtitles.
OwnedScope
FieldTypeDescription
dispose() => voidEnds the scope, aborting signal and running its cleanups.
signalAbortSignalAborts when the scope ends, for fetch calls and the like.
on<Listener extends EventListenerOrEventListenerObject>(target: EventTarget, type: string, listener: Listener, options?: AddEventListenerOptions) => voidAdds an event listener that is removed when the scope ends.
add(cleanup: () => void) => voidRuns cleanup when the scope ends, or immediately if it already has.
Player
FieldTypeDescription
commandsCoreCommandsCore commands, such as play and seek.
clockClockThe clock, for reading and following playback time.
getState() => PlayerStateCurrent state of the whole player.
getInitialState() => PlayerStateState to render on the server and during hydration.
subscribe(listener: () => void) => () => voidCalls listener after state changes, and returns a function that stops it.
onError(listener: (error: MediaErrorInfo) => void) => () => voidCalls listener with every error, fatal or not, and returns a function that stops it. That includes what media.error doesn't keep: blocked plays, and a source that failed when another one took over, which arrives with fatal: false.
plugin<Factory extends AnyPluginFactory>(factory: Factory) => PluginHandle<Factory>Typed access to a plugin's state and commands. Throws if it isn't installed.
has(name: string) => booleanReturns true when a plugin with this name is installed.
announce(message: string) => voidTells screen readers about a change the viewer's focus isn't on, politely, through a hidden live region. It does nothing until the player mounts. Don't call it on a timer or with the time, since every call is spoken.
mount(root?: HTMLElement | null) => () => voidRuns plugin setup hooks. Re-entrant: safe to mount, unmount, and mount again.
attach(element: HTMLVideoElement) => () => voidConnects the media element and begins loading in a microtask.
attributes(state?: PlayerState) => Record<string, string>Root data attributes for the given state.
slot(name: SlotName) => readonly ComponentType[]Components that plugins contributed to a slot, in plugin order.
video() => HTMLVideoElement | nullReturns the video element, or null when none is attached.
root() => HTMLElement | nullReturns the root element, or null when the player isn't mounted.
PlayerOptions
FieldTypeDescription
plugins?readonly AnyPlugin[]The plugins to install, fixed once the player is created.
src?SourceInput | nullThe first source to play, which commands.setSource can replace.
load?LoadStrategyWhen the provider and its engine load. Defaults to eager.
PlayerState
FieldTypeDescription
mediaMediaStateThe kernel's playback state, with each plugin's state beside it under the plugin's name.
PluginContext
FieldTypeDescription
playerPlayerThe player this plugin is installed on.
clockClockThe player's clock, for reading and following playback time.
commandsCoreCommandsThe player's core commands.
state() => StateReads this plugin's current state.
set(state: Partial<State>) => voidMerges changes into this plugin's state.
media() => MediaStateReads the current media state.
report(state: Partial<MediaState>) => voidWrites media state, for plugins that normalize something providers can't.
error(error: MediaErrorInfo) => voidReports a failure, the way a provider does. A fatal one stops playback or moves to the next source.
video() => HTMLVideoElement | nullReturns the video element, or null when none is attached.
root() => HTMLElement | nullReturns the player's root element, or null when it isn't mounted.
watch<Value>(scope: Scope, select: (media: MediaState) => Value, listener: (value: Value, previous: Value) => void) => voidCalls listener whenever the selected value changes, until scope ends.
lock(id: string, commands: readonly LockableCommand[]) => () => voidBlocks commands until the returned function is called.
isLocked(command: LockableCommand) => booleanReturns true when a lock blocks command.
registerProvider(entry: ProviderEntry) => voidAdds a provider to choose from for each source, tried before the native one.
pushProvider(provider: Provider) => () => voidHands playback to provider until the returned function is called.
find<Factory extends AnyPluginFactory>(name: Factory["pluginName"]) => PluginHandle<Factory>Reads an optional dependency without importing its code.
PluginFactory
FieldTypeDescription
pluginNameNameThe plugin's name, as given to definePlugin.
PluginHandle
FieldTypeDescription
state() => StateOf<Factory>Reads the plugin's current state.
commandsCommandsOf<Factory>The commands the plugin offers.
PluginInstance
FieldTypeDescription
nameNameThe plugin's name, which must be unique within a player.
create() => PluginSpec<State, Commands>Builds the spec. Each player calls this, so an instance can be shared safely.
PluginSpec
FieldTypeDescription
requires?readonly string[]Plugins that must be installed. createPlayer throws if one is missing.
after?readonly string[]Plugins that should run first when present.
state?(() => State)Pure. Also runs on the server.
commands?((context: PluginContext<State>) => Commands)Pure. Also runs on the server, so touch the DOM only when a command runs.
attrs?Record<string, (state: State, media: MediaState) => string | number | boolean | null | undefined>Data attributes written to Root as state changes, with no React render.
setup?((context: PluginContext<State>, scope: Scope) => void)Runs from mount to unmount.
attach?((context: PluginContext<State>, element: HTMLVideoElement, scope: Scope) => void)Runs from media attach to detach.
source?((context: PluginContext<State>, source: SourceObject, scope: Scope) => void)Runs for each source until the next one.
gates?Gates<State>Hooks that can change or hold back a load, play, or seek.
slots?Partial<Record<SlotName, ComponentType>>Components rendered by <Slot name>.
Provider

A media engine behind the normalized player interface.

FieldTypeDescription
namestringAppears in MediaState.provider while this provider is active.
attach(element: HTMLVideoElement | null, sink: Sink, scope: Scope) => voidCalled once. element is null for remote providers such as Cast.
load(request: LoadRequest, signal: AbortSignal) => Promise<void>Loads the request, and should stop if signal aborts.
play() => Promise<void>Starts playback, rejecting if the browser refuses.
pause() => voidPauses playback.
seek(time: number) => voidMoves to time, in seconds.
setVolume(volume: number, muted: boolean) => voidApplies the volume, from 0 to 1, and the muted setting.
setRate(rate: number) => voidApplies a playback rate, where 1 is normal speed.
timenumberHot read used by the clock. Must not allocate.
setQuality?((id: string | "auto") => void)Switches to the level with this id, or to automatic choice with auto.
setAudioTrack?((id: string) => void)Switches to the audio track with this id.
setTextTrack?((id: string | null) => void)Uses the text track with this id, or none with null.
snapshot?(() => Partial<MediaState>)Current state, re-applied when the provider resumes from suspension.
destroy() => voidReleases everything the provider holds, when it's removed.
ProviderEntry

Registered by plugins. canPlay must be synchronous and import no engine.

FieldTypeDescription
namestringIdentifies the entry, so registering the same name again replaces it.
canPlay(source: SourceObject, environment: ProviderEnvironment) => booleanReturns true when this provider can play source.
load() => Promise<new () => Provider>Loads the provider's code and resolves to its class.
ProviderEnvironment
FieldTypeDescription
elementHTMLVideoElement | nullThe player's video element, or null if there isn't one yet.
QualityLevel
FieldTypeDescription
idstringIdentifies the level to setQuality and in quality.active.
label?stringName shown in the quality menu.
width?numberWidth in pixels.
height?numberHeight in pixels, which sorts the quality menu.
bitrate?numberBits per second.
Rendition
FieldTypeDescription
label?stringName in the quality menu, defaulting to the height, such as 720p.
width?numberWidth in pixels, passed on to the quality level.
height?numberHeight in pixels, which sorts the quality menu.
bitrate?numberBits per second, passed on to the quality level.
srcstringURL of the media file or stream.
type?stringMIME type, used instead of the URL's extension to choose a provider.
RenditionSet

Selects between progressive files of the same content.

FieldTypeDescription
renditionsRendition[]The files to switch between, one for each quality.
initial?numberIndex of the rendition to start with. Defaults to the first.
Scope
FieldTypeDescription
signalAbortSignalAborts when the scope ends, for fetch calls and the like.
on<Listener extends EventListenerOrEventListenerObject>(target: EventTarget, type: string, listener: Listener, options?: AddEventListenerOptions) => voidAdds an event listener that is removed when the scope ends.
add(cleanup: () => void) => voidRuns cleanup when the scope ends, or immediately if it already has.
Sink

The only way a provider reports state. Ignored while the provider is suspended.

FieldTypeDescription
update(state: Partial<MediaState>) => voidReports changed state, which the player merges into MediaState.
sync() => voidReports that time moved discontinuously, so the clock must write now.
error(error: MediaErrorInfo) => voidReports a failure, which stops playback if it's fatal.
SlotName
SlotName
SourceInput

A single source, a list of fallbacks tried in order, or the renditions of one video. Fallback lists are not quality levels; use renditions for those.

SourceInput
SourceObject
FieldTypeDescription
srcstringURL of the media file or stream.
type?stringMIME type, used instead of the URL's extension to choose a provider.
StateOf
StateOf<Factory>
Timeline
FieldTypeDescription
startnumberEarliest position the viewer can seek to, in seconds.
endnumberLatest position the viewer can seek to, in seconds.
kind"vod" | "live" | "dvr" | "ad"What's playing: on-demand video, a live stream, a live stream with a seek window, or an ad.