This describes the player as it is built, not as it was planned. Every class,
method and event named here exists in packages/*/src. Where a name in an
older revision of this document did not survive contact with the code (the
plugin lifecycle hook has never been called setup, and no package name has
ever carried a plugin- prefix), the name here is the one the code uses.
System overview
+---------------------------------------------------------------+
| Host application |
| createPlayer(options) -> ScarlettPlayer |
| or the Vue wrapper (@scarlett-player/vue) |
| or the CDN embed (@scarlett-player/embed) |
+------------------------------+--------------------------------+
|
+------------------------------v--------------------------------+
| @scarlett-player/core |
| |
| ScarlettPlayer public API, lifecycle, |
| provider selection, load |
| generations |
| |
| PluginManager register / init / destroy, |
| plugin states, dependency |
| order, canPlay() selection |
| |
| PluginAPI what a plugin is handed in |
| init(api): state, events, |
| container, scoped logger, |
| cleanup registration |
| |
| EventBus typed pub/sub over |
| PlayerEventMap, plus |
| interceptors |
| |
| StateManager one Signal per state key, |
| change subscribers, |
| define() for plugin keys |
| |
| ErrorHandler classification, history, |
| emission |
| |
| Logger levelled, scoped per plugin |
+------------------------------+--------------------------------+
|
+------------------------------v--------------------------------+
| Plugins (one npm package each) |
| provider: hls, native, whep |
| ui: ui, audio-ui |
| feature: playlist, captions, chapters, clips, |
| gestures, share, watermark, media-session, |
| airplay, chromecast |
| analytics: analytics |
+---------------------------------------------------------------+
Nothing outside the core layer is required: a host can build a player with a
provider and nothing else. The four plugins that contribute control-bar
controls (playlist, chapters, share, clips) declare @scarlett-player/ui as an
OPTIONAL peer and register their controls through a dynamic import, so they keep
working when no UI package is installed.
@scarlett-player/ui exposes two extension seams, both through module-level
registries rather than through IPluginAPI, and both feature-detected by their
callers:
- The control registry (
registerControl) contributes a button to a slot in the bar, which the host's layout has to name for it to appear. - The timeline registry (
registerTimelineExtension) contributes an editing layer over the playback rail: a positioned element with the rail's exact horizontal geometry, plus leases for holding the bar visible and for suppressing ordinary seeking while the extension owns a pointer. One extension per player, keyed by container.@scarlett-player/clipsmounts its in/out handles there and falls back to a self-contained rail when the seam is absent, so an older UI peer degrades rather than failing.
Both registries are keyed by the player container where per-player state is involved, which is what keeps two players on one page from driving each other's controls.
Packages
Nineteen packages, all published at one version by a fixed Changesets group.
| Path | Package |
|---|---|
packages/core |
@scarlett-player/core |
packages/vue |
@scarlett-player/vue |
packages/embed |
@scarlett-player/embed |
packages/plugins/hls |
@scarlett-player/hls |
packages/plugins/native |
@scarlett-player/native |
packages/plugins/whep |
@scarlett-player/whep |
packages/plugins/ui |
@scarlett-player/ui |
packages/plugins/audio-ui |
@scarlett-player/audio-ui |
packages/plugins/playlist |
@scarlett-player/playlist |
packages/plugins/captions |
@scarlett-player/captions |
packages/plugins/chapters |
@scarlett-player/chapters |
packages/plugins/gestures |
@scarlett-player/gestures |
packages/plugins/share |
@scarlett-player/share |
packages/plugins/clips |
@scarlett-player/clips |
packages/plugins/watermark |
@scarlett-player/watermark |
packages/plugins/media-session |
@scarlett-player/media-session |
packages/plugins/airplay |
@scarlett-player/airplay |
packages/plugins/chromecast |
@scarlett-player/chromecast |
packages/plugins/analytics |
@scarlett-player/analytics |
There is no React package and no presets package. Every directory under
packages/plugins/ is one of the sixteen plugin packages above; the empty
placeholder directories that used to sit beside them were deleted on
2026-09-02. A name under packages/plugins/ means a package only when it has a
package.json.
Lifecycle
Construction
new ScarlettPlayer(options) resolves the container (an HTMLElement or a CSS
selector, throwing when neither resolves), builds the EventBus,
StateManager, Logger, ErrorHandler and PluginManager, wires the three
listeners that keep the error state key in sync (error sets it,
media:loaded clears it, media:error is recorded through
ErrorHandler.record() without flipping the state), wires the four fullscreen
listeners through the private wireFullscreenListeners() (see Fullscreen
below), and calls PluginManager.register() for each plugin in
options.plugins.
Registration is all the constructor does to plugins. No plugin's init() runs
yet, and no source is loaded.
Initialisation
init() and load() both go through the private ensureInitialized(), which
is idempotent and safe to call re-entrantly. One pass (runInitialization()):
- Walk
PluginManager.getPluginIds(). For every plugin that is nottype: 'provider'and is still in theregisteredstate, callPluginManager.initPlugin(). Plugins in any other state are skipped, so a plugin added throughregisterPlugin()after start-up is picked up by the next call and nothing is initialised twice. wireLifecycleListeners(), guarded by the privatelistenersWiredflag so the two listeners it installs exist exactly once no matter how many timesload()runs.- Emit
player:ready, guarded by the privatereadyEmittedflag so it is emitted at the end of the FIRST pass only.
ensureInitialized() returns the in-flight promise when a pass is already
running. That matters because one of the listeners wired in step 2 calls
load(), which calls ensureInitialized() again: without the shared promise,
initPlugin() would find a plugin in the initializing state and throw
"possible circular dependency".
init() is ensureInitialized() followed by a load() of options.src when
one was given. createPlayer(options) is new ScarlettPlayer(options) plus
await player.init(), and is the documented entry point.
load() calls ensureInitialized() before it selects a provider, so
constructing a player and calling load() without init() produces a fully
wired player rather than a provider with no UI, no error overlay and no working
playlist. That shape was widely copied out of the READMEs, which is why the
auto-initialisation exists.
Two listeners are installed by wireLifecycleListeners():
media:load-request(emitted by the playlist plugin, among others): loads the requested source, handing the payload'sautoplaytoload()as an override of theautoplayoption for that load, so it plays unless the payload saysautoplay: false, whatever the option. It returns early while Chromecast is active, because the Chromecast plugin owns loading then.error:retry(emitted by the UI error overlay's Try Again button): reloads through the normal provider path, then restores position, live streams at the live edge throughseekToLive(), VOD at the previouscurrentTime.
Both handlers re-check the destroyed flag after each await. They are unawaited
async closures, so a read against a torn-down StateManager would surface as an
unhandled rejection rather than a caught error.
player:ready
Emitted once, at the end of the first initialisation pass. It used to be the
constructor's last statement, where no consumer and no plugin could have
subscribed yet, so no listener could ever observe it. A host that wants the
event subscribes between construction and the first init()/load(); a host
using createPlayer() has the returned promise as its readiness signal and does
not need the event at all.
Loading a source
load(source):
- Increments
loadGenerationand captures the value. Every post-await step compares against it and bails when a newerload()(or adestroy(), which also increments the counter) has started. - Resets the playback state keys through
StateManager.update()and clearserror. - Destroys the previous provider through
PluginManager.destroyPlugin(), which returns it to theregisteredstate so it can be initialised again later, then waits for any teardown anunload()still has in flight. Each wait is bounded at 10 seconds: past that the player logs a warning, cuts the old provider off (see below) and goes ahead, and the old provider's teardown finishes whenever it settles. ensureInitialized().PluginManager.selectProvider(source). No provider meansErrorHandler.throw(ErrorCode.PROVIDER_NOT_FOUND, ...)and a return, not an exception.PluginManager.initPlugin()for the selected provider only. Providers are initialised lazily, per source; every other plugin was initialised in step 4.- Writes
sourcestate (srcplus the MIME type derived by the privatedetectMimeType()), calls the provider'sloadSource(), and plays when theautoplaystate key is set, unless the caller passed anautoplayoverride (load(src, { autoplay })), which decides for that load alone.
Failures inside load() are reported, never thrown at the caller: when the
error state is already populated (a provider that emitted a structured fatal
error of its own) the catch only logs, so a specific code is not overwritten by
a generic one.
When the returned promise settles. load() awaits the provider's
loadSource(). A source failure does not reject it: core reports the failure
through the error state and the error event, then resolves. load() rejects
only when the player has been destroyed. The two providers that reconnect
differ in how long they hold it:
- HLS (hls.js and native) keeps
load()pending through its in-place retries (maxNetworkRetries,maxMediaRetries), then settles as soon as it reports the fatalerror. On a live source that error carriesdetail.reconnecting: trueand auto-reconnect carries on behind the settled promise. - WHEP keeps
load()pending while its reconnect scheduler is trying, up toreconnectWindowMs(five minutes by default). A stream that has not started yet, or is at its monitor cap, is a wait rather than a failure. Terminal failures - a refused token, a missing stream, an endpoint that does not speak the protocol - are not scheduled for reconnect and settle in seconds.
Either way, the promise is not the progress channel. Hosts follow
error:reconnecting, error:recovered and fatal error; a host that needs a
hard bound on WHEP sets a shorter reconnectWindowMs or races the promise.
Unloading a source
unload() leaves the current source and keeps the player. With nothing loaded
or loading it returns without doing anything. Otherwise it:
Increments
loadGeneration, so an in-flightload()bails at its next checkpoint, and clears the pending seek-resume timeout. A secondunload()before the first finishes, with noload()between, shares its promise.Destroys the active provider through
PluginManager.destroyPlugin(), which closes its connection or pipeline and removes its media element; a provider still inside itsinit()is destroyed once that settles. The wait is bounded at 10 seconds (PROVIDER_TEARDOWN_TIMEOUT_MS, internal, not an option): when the provider'sinit()ordestroy()has not settled by then, the player logs a warning and goes on to the next steps, and the teardown finishes whenever it settles. A laterload()that selects the same provider still waits for that teardown ininitPlugin();destroy()releases a bounded wait at once.When the bound fires, the player first cuts the old provider off (
PluginManager.abandonPlugin()): itsPluginAPIruns its cleanups and is revoked, sosetState,defineState,emit,onandsubscribeToStatedo nothing andapi.containeris a detached stand-in, and the media elements in the player's container are paused and removed. Only the first bound to fire for a teardown does this, while no other provider is active, so the latedestroy()cannot remove a replacement's reused element or write to its state. A freshinitPlugin()restores the API.Applies the unloaded state:
sourcenull,playbackStateidle, theplayingfalse,pausedtrue,ended,buffering,waitingandseekingfalse,currentTime,durationandbufferedAmount0,bufferedanderrornull,mediaTypeunknown,qualities,audioTracksandtextTracksempty,currentQuality,currentAudioTrackandcurrentTextTracknull,liveandliveEdgefalse,seekableRangenull,liveLatency0 andlowLatencyModefalse.poster,title,chapters,thumbnailsand the viewer's volume, mute, rate and autoplay settings are left alone by this core reset. The core README lists every key it resets and leaves alone; plugins can update state during teardown.Emits
source:unloadedwith{ src }, the source the lastload()asked for.
When a newer load() starts while the provider is going down, that load owns
the state: the unload applies nothing and emits nothing, and the load waits
for that teardown (up to the same 10-second bound) before it selects a
provider, the same one or another. unload() rejects
after destroy(), and the next load() works as on a fresh instance. The
analytics plugin ends its open view as abandoned on source:unloaded, and
the Chromecast plugin stops the media on the receiver while keeping the
session.
Destruction
destroy() increments loadGeneration so in-flight loads self-cancel through
the mechanism load() already trusts, clears the pending seek-resume timeout,
removes the four fullscreen listeners, emits player:destroy, then
PluginManager.destroyAll(), EventBus.destroy() and StateManager.destroy(). Every public method calls the private
checkDestroyed() first and throws on a destroyed player. The state getters do
not: they read through StateManager, which raises its own destroyed-specific
error rather than the misleading unknown-key one.
PluginManager
register(plugin, config?) validates the plugin (id, name, version,
type, init, destroy all present and of the right kind), rejects a
duplicate id, builds that plugin's PluginAPI, stores the record in the
registered state and emits plugin:registered.
PluginState is registered, initializing, ready, error or destroyed.
initPlugin(id) returns immediately when the plugin is already ready, throws
when it is initializing (the circular-dependency guard), initialises any
entries in the plugin's dependencies array first, subscribes the plugin's
optional onStateChange and onError hooks (unsubscribing them through
api.onDestroy()), then awaits plugin.init(api, config). Success emits
plugin:active; a throw sets the error state, emits plugin:error and
rethrows.
destroyPlugin(id) awaits plugin.destroy(), runs the API's registered cleanup
functions and resets the record to registered so the plugin can be
initialised again. A destroy requested while the plugin's init() is still
running waits for that init to settle and then destroys it, so a provider switch
or unload() mid-init cannot leave it running with live listeners; an init
that fails still has its registered cleanups run. Concurrent calls share one
teardown, and an initPlugin() made during a teardown waits for it and then
runs a fresh init(). destroyAll() is the exception to the waiting: the
player's own destroy() does not wait for a plugin still inside init()
(that init may depend on a script that never arrives), so that plugin is
destroyed later, if and when its init settles. initAll() and destroyAll() walk
resolveDependencyOrder(), a topological sort that throws
Circular dependency detected with the cycle path; destroyAll() walks it in
reverse.
getPlugin(id) returns any registered plugin. getReadyPlugin(id) returns it
only when it is ready, and is what IPluginAPI.getPlugin() is wired to, so a
plugin can never reach another plugin that has not finished initialising.
Provider selection
selectProvider(source) takes the plugins with type: 'provider' in
registration order and returns the first whose canPlay(source) returns true.
There is no priority table and no scoring: registration order is the priority,
so a host that wants HLS to win registers createHLSPlugin() before
createNativePlugin().
@scarlett-player/hls:canPlay()accepts a source whose path ends in.m3u8or whose URL carries an mpegurl MIME hint, regardless of browser support. A browser with neither hls.js (MSE) nor native HLS getsErrorCode.SOURCE_NOT_SUPPORTEDfromload(), with the support probe results in the error message and undercontext.probes.@scarlett-player/native:canPlay()requires a known extension and a positiveHTMLMediaElement.canPlayType()answer for the mapped MIME type.
A source no provider accepts produces ErrorCode.PROVIDER_NOT_FOUND.
Plugin interface
interface Plugin<TConfig extends PluginConfig = PluginConfig> {
readonly id: string;
readonly name: string;
readonly version: string;
readonly type: PluginType;
readonly description?: string;
readonly dependencies?: string[];
init(api: IPluginAPI, config?: TConfig): void | Promise<void>;
destroy(): void | Promise<void>;
onStateChange?(event: StateChangeEvent): void;
onError?(error: Error): void;
getDiagnostics?(): unknown;
}
type PluginType = 'provider' | 'ui' | 'feature' | 'analytics' | 'utility';
The lifecycle hook is init(api). There is no setup(), and destroy() is
required, not optional.
A provider adds canPlay(src: string): boolean and
loadSource(src: string): Promise<void>; ScarlettPlayer calls both by duck
typing rather than through a separate interface, and proxies getLevels(),
setLevel(), getCurrentLevel() and getLiveInfo() the same way, so a
provider that implements none of them still works.
Plugins expose an imperative API by hanging methods off the same object
(@scarlett-player/playlist is the example: add(), play(), next(),
previous()), which a host reaches through player.getPlugin(id).
PluginFactory is the exported type for the createXPlugin(config?) factory
functions every package ships.
Diagnostics snapshots
player.getDiagnostics() returns a synchronous, side-effect free
PlayerDiagnosticsSnapshot with schemaVersion: 1: a whitelisted projection of
playback state, the recent structured errors from the error handler's history,
and a providers map keyed by plugin id. It works before playback, during an
outage and after destroy() (which returns a destroyed snapshot with no
errors or providers), and it never mutates player or analytics state.
Only ready plugins of type provider are asked for a contribution, through the
optional getDiagnostics() hook. Core treats every contribution as untrusted:
a provider without the hook maps to null; one that throws or returns a promise
maps to { unavailable: true }. Anything else is reduced to finite numbers,
booleans, null and a short allowlist of categorical strings (the HLS engine and
the WebRTC connection, ICE and signaling states), inside plain objects and arrays
(typed arrays, Map, Set, Date, class instances and DOM nodes are dropped).
Each contribution is capped at 4 levels of nesting (applied to primitives too),
64 keys per object, 50 items per array and 500 values in total. Keys must match
[A-Za-z][A-Za-z0-9_]{0,39} and must not be identity or location-like (id,
userId, viewerId, uid, email, ip, url, uri, src, href, key).
Every other string is dropped, because a secret or an identifier can sit anywhere
in free text and no redaction pattern makes it safe; sensitive-looking keys,
cycles and prototype keys are dropped too. When the error history is longer than
the cap of 20, the newest errors are kept.
The snapshot's truncatedProviders lists the providers whose contribution lost
anything that way. A hook that calls back into collection gets an empty map. The
HLS, native and WHEP providers contribute their own fields; the analytics plugin
exposes a separate getDiagnostics() with its current, non-mutating metric
totals and only known error codes and categories.
IPluginAPI
The whole surface a plugin is handed. PluginAPI in
packages/core/src/plugin-api.ts is the implementation; the interface lives in
packages/core/src/types/plugin.ts.
| Member | Purpose |
|---|---|
pluginId |
The plugin's own id |
container |
The player container element |
logger |
debug/info/warn/error, prefixed with the plugin id |
getState(key) |
Read one state key, typed by StateValue<K> |
setState(key, value) |
Write one state key |
defineState(key, initialValue) |
Register a key this plugin owns, before first use |
on(event, handler) |
Subscribe; returns an unsubscribe function |
off(event, handler) |
Unsubscribe |
emit(event, payload) |
Emit a typed event |
getPlugin(id) |
Another plugin, only if it is ready |
onDestroy(cleanup) |
Register a cleanup function |
subscribeToState(callback) |
Every state change, as a StateChangeEvent |
getProviderDiagnostics() |
Sanitized diagnostics from the ready providers, keyed by plugin id (what player.getDiagnostics() puts under providers) |
There is no play(), pause() or seek() on the API: a plugin drives playback
by emitting playback:play, playback:pause or playback:seeking, which the
active provider is subscribed to. That keeps plugins independent of which
provider is loaded.
playback:seeking { time } is a seek request, not a notification of every
element seek. Core, gestures, media-session and UI controls can emit it. The
video UI emits after its direct currentTime write: progress-bar press and
release (not every throttled drag move), keyboard seeks, the skip buttons and
control-bar replay. The chapters plugin emits it for live chapter seeks.
HLS and native providers instead handle the element's seeking by publishing
its target currentTime before seeking: true; they do not re-emit the
command and create a feedback loop. Analytics observes both paths, consuming
recent bus echoes to avoid double-counting, and labels its seeking beacons
with seekSource: 'player' or 'element'. The echo window includes 1000 ms;
expired pending echoes are discarded before recording a new bus request.
Both seek paths are ignored for analytics after viewEnd until the next view
opens (a play request, or a load of another source), so replay preparation
cannot alter a finalized view.
runCleanups(), getCleanupFns(), revoke() and restore() exist on the
concrete PluginAPI for PluginManager to call; they are marked @internal
and are not part of IPluginAPI.
State
StateManager holds one Signal per key. DEFAULT_STATE supplies the initial
values and is typed against CoreStateStore, not StateStore:
CoreStateStoreis the closed set of keys core owns, soDEFAULT_STATEcan be exhaustive over exactly those keys.StateStore extends CoreStateStoreand is open. A plugin adds the state it owns by declaration merging intoStateStore, so augmenting it cannot break core's own compilation with a "missing properties" error.
At runtime the store is closed too: get() throws Unknown state key for a key
nobody registered, which is a deliberate typo-catcher. A plugin therefore calls
api.defineState(key, initialValue) in init() before first use. define() is
idempotent: re-defining an existing key keeps the current value, because plugins
re-run setup after a source change and that must not wipe live state. The
initial value is remembered in definedDefaults so reset() and resetKey()
work on plugin keys, which have no entry in DEFAULT_STATE.
Reads and writes: get(key) (the Signal), getValue(key), set(key, value),
update(partial), snapshot() (a frozen StateStore), reset(),
resetKey(key). Subscriptions: subscribeToKey(key, cb) for one key,
subscribe(cb) for every change. ScarlettPlayer.getState() returns
snapshot().
After destroy(), get() throws a destroyed-specific message rather than the
unknown-key one. Returning last-known values instead was considered and
rejected: it masks the lifecycle bugs the throw exposes.
The signal primitives (Signal, signal, Computed, computed, effect, and
the currentEffect tracking helpers) are exported from core for consumers that
want them directly.
Events
PlayerEventMap is the single typed map of event name to payload; EventName,
EventPayload<T> and EventHandler<T> derive from it. Like StateStore, it is
an interface, so a plugin adds its own events by declaration merging without a
core change.
Core owns these namespaces: player:, playback:, media:, volume:,
quality:, track:, fullscreen:, pip:, airplay:, chromecast:, live:,
chapter:, gesture:, controls:, ui:, state:, plugin:, error: and
playlist:, plus the single unnamespaced error. A plugin namespaces its own
events with its plugin id.
media:segment carries { durationMs, bytes, ok, kind } for measured hls.js
fragment loads and failures (kind is main, audio or subtitle). Duration
is the request's loading interval in milliseconds; on non-fatal fragment errors
and timeouts where hls.js leaves loading.end at zero, the plugin uses
performance.now() - loading.start when both timing and loaded bytes are
measurable. bytes is the amount loaded. A provider without those measurements
does not emit the event: native Safari HLS, progressive media and WHEP do not
report fabricated zero-valued segments. Both HLS entries share this mapping.
Analytics aggregates the available measurements by heartbeat/final view end
into segmentCount, segmentBytes, segmentLoadAvgMs, segmentLoadMaxMs,
segmentThroughputBps (from main fragments when timed) and segmentErrors;
it omits these keys without measurements. Decoded/dropped frame deltas are
reported only when the media element exposes getVideoPlaybackQuality().
EventBus provides on, once, off, emit, emitAsync, intercept,
removeAllListeners, listenerCount and destroy. A handler that throws is
caught and logged, so one bad listener cannot stop the others. An
EventInterceptor runs before the handlers and can rewrite the payload or
cancel the event by returning null; interceptors are enabled by default and
can be turned off through EventEmitterOptions.
Analytics timing and ordering
videoStart marks a confirmed first frame, not the first playing event:
the first requestVideoFrameCallback on the element, or else the first
timeupdate whose position has moved past the play request's
(firstFrameSource: 'rvfc' | 'progress'). startupTime runs to that
confirmation and no playTime accrues before it. A seek before the first
frame re-arms confirmation when it ends, measured from the post-seek
position, and progress is also read from the element's own timeupdate, so
WHEP confirms without rVFC. While casting, the receiver's advancing position
confirms instead, since the local element stays paused. Safari can fire playing
right after play without showing a frame, which made iOS startup times read
1-7 ms. A view that never confirms sends no videoStart, so a view that
older releases counted as started on iOS now counts as not started.
A view that never confirms says why on its viewEnd as startState:
played, awaitingTap, failed or never. When the browser's autoplay
policy rejects play() with NotAllowedError, the provider emits
playback:blocked (PlaybackState is unchanged), analytics sends a
playBlocked beacon and the view is awaitingTap until the viewer plays, so
"waiting for a tap" is separate from "stream failed". A failed plugin init
(plugin:error) and an error payload with no code or message are reported
as error beacons instead of being dropped.
The analytics plugin waits rebufferGraceMs (250 ms by default) before counting
an eligible post-first-frame stall. A stall that the browser never reports
with waiting counts too: while the view is playing, visible and past its
first frame, the position is sampled every 500 ms, and 2 s without progress
opens a rebuffer backdated to the last advance (rebufferStart.cause:
'waiting', 'progress' or 'reconnect'). Sampling is off while a
Chromecast session is active (chromecastActive). A beacon sent during a
freeze not yet confirmed as a stall reports play and DVR credit only up to
the last advance, so cumulative counters never decrease. Zero counts synchronously; negative or
non-finite values fall back to 250 ms. Resuming, pausing, seeking or closing
the view during the grace cancels the pending rebuffer. Confirmed duration
includes the grace, but rebufferStart.timestamp remains its send time, not
the original waiting time. Pending waiting contributes to watch time, never
play time, even when too short to count as a rebuffer.
Every dispatched beacon has a per-view beaconSeq, starting at 1 on
viewStart, assigned after development/error-sampling filters and protected
from custom-data overrides. Custom events and unload beacons share the counter.
Order each view by timestamp, beaconSeq, not arrival or row ID.
timestamp is the client clock when the event happened. Every unbatched POST
body, and each batch envelope (events inside a batch carry none), also
carries sentAt, the client clock when it left the
browser, stamped after headers() resolves and outside beforeSend; a sentAt from customDimensions or beforeSend is
dropped. An
ingest corrects client clock skew with receipt - sentAt and applies that
offset to timestamp; customBeacon payloads carry no sentAt. An ingest
that drops heartbeats sees sequence gaps. seeking carries seekSource
(player or element); a view closes seek accounting at viewEnd. The
hei/laravel-scarlett-player v0.3.0 migration recognises the 1.19.3
ordering/source fields, not opt-in batch envelopes.
Heartbeats and ordinary final viewEnd carry continuous QoE
qoeVersion: 3; fatal access denial produces qoeScore: null, and a view with no
first frame is scored by cause (0 if it asked to play, null if it never asked or is
awaiting a tap). Heartbeats and
both viewEnds (ordinary and unload) are built from one cumulative-metrics
builder, so they carry the same counters and scores. Structured error
beacons classify code/detail into errorCategory and errorSeverity (an
element error falls back to its MediaError code), expose only validated
diagnostic fields plus online and the source's host name, and avoid raw
signed URLs. warningCount and (on fatal ends) fatalErrorCategory
accompany view metrics. A closed view stays closed: after its viewEnd no
error, pause, rebuffer, quality or visibility beacon is sent for it. A fatal
error whose detail.reconnecting is true is a warning that leaves the view
open, with the outage reported as reconnecting/recovered beacons. A view
not playing for idleTimeout (30 minutes by default) ends as abandoned.
Analytics has no default endpoint: the host must configure beaconUrl.
respectDoNotTrack honors DNT/GPC by suppressing beacons; anonymous uses
per-view IDs without storage, and setAnonymous() changes the next view.
beforeSend may modify or drop normal and unload payloads. null drops a
beacon; other non-object results preserve the original payload and consume
its sequence number once. On viewStart,
pageUrl is origin plus pathname only, referrerOrigin omits paths, and
pageLoadToInitMs/optional playerInitMs capture context. batch defaults
off, preserving one POST per beacon; opt-in sends a bounded
{ batch: 1, sentAt, events } envelope and needs a compatible custom ingest.
Laravel v0.3.0 rejects batch requests with 422. Its default CDN embed pin
is 1.19.1, so newer data-analytics-anonymous,
data-analytics-respect-dnt and data-analytics-batch attributes only work
when the embed bundle is separately repinned to a version that supports them;
an attribute alone never enables analytics without data-analytics-beacon-url.
See the analytics README for the
full accounting and wire contract.
Error and reconnect model
ErrorHandler normalises anything thrown into a PlayerError
(code, message, fatal, timestamp, optional context, originalError
and detail), keeps a bounded history (ten entries by default), logs it at
error level when fatal and warn level otherwise, and emits error.
handle(error, context)does all of that.record(error, context)does everything except emit, for advisory channels: media element errors go through it so they are visible ingetHistory()without flipping the error state that the retry flow reads.throw(code, message, options)builds aPlayerErrorfrom anErrorCodeand handles it. It does not throw a JavaScript exception.
ErrorCode covers source loading (SOURCE_NOT_SUPPORTED,
SOURCE_LOAD_FAILED), providers (PROVIDER_NOT_FOUND,
PROVIDER_SETUP_FAILED), plugins (PLUGIN_SETUP_FAILED, PLUGIN_NOT_FOUND),
playback and media (PLAYBACK_FAILED, MEDIA_DECODE_ERROR,
MEDIA_NETWORK_ERROR, MEDIA_APPEND_ERROR, MEDIA_BUFFER_FULL,
PLAYLIST_INVALID) and UNKNOWN_ERROR. SOURCE_NOT_SUPPORTED,
PROVIDER_NOT_FOUND and MEDIA_DECODE_ERROR are classified fatal by default.
Providers attach diagnostics through PlayerErrorDetail: type,
retriesExhausted, attempts, reconnectExhausted, reconnecting,
httpStatus, url, mediaErrorCode, mediaErrorMessage, networkState,
readyState and timedOut. reconnecting: true marks a fatal error the
provider will try to recover from by auto-reconnecting; it is absent on
terminal errors. It also rides on the non-fatal media:error for the first
failed native reload of an outage.
url must be sanitised by the provider before it is set. The HLS plugin does
that with its exported sanitizeUrl(), which strips the query string and the
fragment, keeps origin plus pathname, and replaces path segments that look like
tokens with :redacted. Only two shapes are recognised: a segment that is a
hex run of 32+ characters, and an underscore-joined <expiry>_<nonce>_<sig>
segment with a signature-like part. A credential in any other path shape is not
caught, so a consumer using one scrubs the path on its own side before
forwarding the value to telemetry.
Recovery lives in the provider, not in core. In @scarlett-player/hls:
- Bounded retries first, with jittered exponential backoff:
maxNetworkRetries(default 3) andmaxMediaRetries(default 2). Both budgets apply on the hls.js branch and, throughhandleNativeFatalError(), on the native Safari branch, where recovery means reloading the source and restoring the position captured at the first failure. The budgets reset once media flows again, so a long event's transient blips never accumulate. - The native first load spends the same budgets inside
loadNative(), beforeloadedmetadata:MEDIA_ERR_DECODEis a media error and every other code a network one, since Safari reports a failed manifest asMEDIA_ERR_SRC_NOT_SUPPORTED. Afterloadedmetadata, onlyMEDIA_ERR_NETWORKis a network error.loadTimeoutMsis one ceiling over the whole load and wins over any budget left. Every terminal outcome goes throughemitFatalError()before the load rejects, with the element'smediaErrorCodeandmediaErrorMessage(andtimedOutfor the watchdog) indetail, so core'sload()keeps the provider's code. emitFatalError()emits the fatalerrorand then callsmaybeScheduleReconnect(), which hands over to the auto-reconnect scheduler only when the failure was a network or media one and playback had already started, the stream is live, or the failure is a load timeout (detail.timedOut), as is any later failure inside the window a timeout opened. A stall atloadTimeoutMsis transient and comes before live is known, so both watchdogs hand it to reconnect (the native one first tears down and aborts the stalled element fetch);load()still rejects at the timeout, and a load that later recovers plays when its effective autoplay was on. A wrong URL errors rather than stalls, so it stays a manual fatal before playback. That gate,canAutoReconnect(), is checked before the emit as well, so the fatalerroralready carriesdetail.reconnecting: truewhen a reconnect will follow.scheduleReconnectAttempt()emitserror:reconnecting({ attempt, delayMs, elapsedMs?, windowMs? }) andattemptReconnect()rebuilds the pipeline, resuming VOD at the position captured at the first failure. Native live reloads rejoin the edge even when the viewer was behind it in the DVR window. On hls.js the new instance retains configuredstartPosition; the default-1selectsliveSyncPositionunlessEXT-X-STARTtakes precedence. No saved live DVR position is restored. On native HLS,rejoinNativeLiveEdge()seeks to the last seekable end minus target latency, clamped to that range's start, unless playback is within edge tolerance or a viewer seek is in progress. When no range exists at metadata, it waits forcanplay,progressordurationchange; a viewer seek or teardown cancels the pending rejoin. Native error recovery does the same. The initial native load preserves Safari's or the host's chosen start. A qualifying fatal error can still carry the marker after the window has run out; the scheduler then emitserror:reconnect-exhaustedand the final unmarked fatalerrorimmediately, with no interveningerror:reconnecting.- Giving up is decided by a TIME WINDOW (
reconnectWindowMs, default 300000ms), not by an attempt count, which is why the payload reportselapsedMs/windowMsand there is nomaxAttemptsto render against. emitReconnectExhausted()closes the cycle exactly once, behind a latch thatcancelReconnect()clears: it emitserror:reconnect-exhausted({ attempts, elapsedMs, windowMs }) and then a final fatalerrorcarryingdetail.reconnectExhausted. The final error deliberately does not go throughemitFatalError(), which would re-enter the scheduler.- A mid-playback stall has its own ceiling,
stallTimeoutMs(default 120000ms, 0 disables), because live has no reconnect window and a reload that stalls again would otherwise start over. The clock starts at the first stall detection, survivescancelReconnect(true)after a "successful" reconnect and resets only on real playback progress. At the ceiling the sameemitReconnectExhausted()path runs withdetail.stalled: true. Hidden, offline and paused time is not counted.
For a scheduled reconnect cycle, the ordering a UI can rely on is one or more
error:reconnecting, then
exactly one of error:recovered or error:reconnect-exhausted. A consumer that
shows a reconnecting state on the first can take it down on either terminator
and will never be stranded.
The UI plugin's ErrorOverlay renders viewer-facing copy per ErrorCode, shows
the reconnecting state while the provider self-heals, and emits error:retry
when Try Again is pressed, which core's own listener turns back into a load().
Live and low latency
Five state keys describe a live stream - live, liveEdge, seekableRange,
liveLatency and lowLatencyMode - and four events announce changes to them:
live:edgechange, live:latency, live:seekablerange and live:lowlatency.
One writer. packages/plugins/hls/src/live-metrics.ts is the only place
that writes four of those five keys. computeLiveMetrics(source) measures, and
applyLiveMetrics(api, metrics) writes and emits, each key only when its value
actually changed. hlsLevelLoaded owns live itself and nothing else does.
That rule exists because it was broken. hlsLevelLoaded used to compute an edge
flag from the playlist and the timeupdate handler then recomputed it four
times a second as latency < 10 off video.seekable - the wrong source under
MSE, where seekable.start(0) stays 0 instead of following the sliding window,
and a threshold that is unconditionally true at a 2-4 second low-latency target.
"GO LIVE" could not appear however far a viewer drifted. Anything that needs a
new live reading calls computeLiveMetrics; nothing writes those keys directly.
Latency truth differs by path. On hls.js (MSE), hls.latency is real
wall-clock latency measured against EXT-X-PROGRAM-DATE-TIME drift where the
manifest carries it, and hls.targetLatency derives from PART-HOLD-BACK /
HOLD-BACK. On the native path (Safari/iOS) there is no latency API, so the
distance to video.seekable.end stands in - a buffer distance, not a latency -
and the edge threshold stays deliberately loose (the historical 10s) unless a
target latency carried over from an hls.js session on the same source.
A viewer is at the edge when latency <= targetLatency + tolerance, with
tolerance = max(1.5, partTarget ?? targetduration / 2). That formula is what
decides when "GO LIVE" appears, and the UI's time readout follows the same
liveEdge flag: blank at the edge, -m:ss behind live once it clears.
lowLatencyMode reports effect, not intent. It is true only when the
manifest carries EXT-X-PART or advertises CAN-BLOCK-RELOAD=YES and the
host asked for low latency in the HLS plugin config. A flag set against a plain
live manifest gets no badge, and neither does an LL manifest played without the
flag - hls.js will not load its parts.
Rejoining the edge goes through core. A control emits live:seektolive;
ScarlettPlayer subscribes and calls seekToLive(), which prefers the
provider's liveSyncPosition and only then falls back to seekableRange.end
and duration. The two are not interchangeable under low latency: the end of
the seekable range is past the last loaded part, and seeking there stalls. The
UI's LiveIndicator used to seek there itself; it now carries no target at all.
The same rule covers every other live seek: the HLS provider clamps each
playback:seeking request to [window start, liveSyncPosition], so a
progress-bar drag or End key to the end of the window lands at the sync
position instead of stalling. VOD seeks still clamp to [0, duration].
Fullscreen
Core owns fullscreen since 1.8.0. packages/core/src/fullscreen.ts exports
enterFullscreen(container), exitFullscreen(container) and
isFullscreen(container) as runtime exports, and every way in goes through
them: ScarlettPlayer.requestFullscreen(), exitFullscreen() and
toggleFullscreen(), the UI package's FullscreenButton and its f shortcut.
Before that there were three implementations, and only the button carried the
iPhone fallback, so player.requestFullscreen() (what the Vue wrapper and the
useScarlettPlayer composable call) did nothing at all on an iPhone.
enterFullscreen()triesElement.requestFullscreen, thenwebkitRequestFullscreen, then the iPhone'svideo.webkitEnterFullscreen()on the container's video element, looked up on every call because a provider creates that element per source. Exhausting all three throws rather than resolving: a silent no-op would arm the optimistic write below and announce a transition that never happened.exitFullscreen()checks the video'swebkitDisplayingFullscreenFIRST and callswebkitExitFullscreen()there, because a WebKit that exposesdocument.exitFullscreenwhile the native player is up has no fullscreen element and would reject. Thendocument.exitFullscreen, thenwebkitExitFullscreen.isFullscreen()reads the browser (fullscreenElement,webkitFullscreenElement,webkitDisplayingFullscreen), never the state key, so a stale key cannot invert a toggle.
The fullscreen state key is written from real browser events. The player
listens for fullscreenchange and webkitfullscreenchange on the document,
and for webkitbeginfullscreen and webkitendfullscreen in the capture phase
on its container, because those two are dispatched on the video element and do
not bubble. Each one calls the private setFullscreenState(), which writes the
key and emits fullscreen:change only when the value actually changed. The
spec fires fullscreenchange before requestFullscreen() resolves, so the
optimistic write that follows the await in requestFullscreen() and
exitFullscreen() runs only where the browser stayed silent (the private
fullscreenAnnounced flag): jsdom never fires the event, and neither does the
iPhone's native player until it has finished opening. All four listeners are
removed in destroy().
Data flow
host call or user gesture
|
v
ScarlettPlayer method -> EventBus.emit(...)
| |
| v
| interceptors (may rewrite or cancel)
| |
| v
| plugin handlers, provider handlers
v |
StateManager.set/update <-------+
|
v
signal subscribers -> StateManager change subscribers
| |
v v
plugin.onStateChange api.subscribeToState(...)
|
v
UI controls redraw
Playback state is written by the provider from real media element events, not
optimistically by the player: play() emits playback:play and lets the
provider report what actually happened, because setting playing: true up front
caused state to drift from the element.
Build and distribution
@scarlett-player/core,@scarlett-player/vueand@scarlett-player/embedbuild with Vite; every plugin builds with tsup and emits its own declarations throughdts: truein itstsup.config.ts, which alsodefines the package's own version forsrc/version.ts. Core's build isrimraf dist tsconfig.tsbuildinfo && tsc && vite build:tscemits declarations only (emitDeclarationOnly) and Vite writes the runtime bundles into the samedist, so the Vite config pinsemptyOutDir: false. Emptyingdistbetween the two steps would delete the declarations thattypesand every plugin's tsconfigpathspoint at.- Every package restricts
filesto its build output, so nothing butdistis published (embed also ships itsiframe.html). - hls.js is loaded lazily by
loadHlsJs()through a dynamicimport, so a page that never plays HLS never fetches it.@scarlett-player/hls/lightis a second entry over the same factory (src/create-hls-plugin.ts) built on hls.js/light: no subtitles, no ID3, no DRM. - The playlist plugin registers its control-bar controls through
void import('@scarlett-player/ui')and logs and continues when the UI package is absent, which is what makes it work headless. - Versioning is Changesets in fixed mode: all nineteen packages share one version number.
Testing
- Vitest per package, with jsdom.
pnpm testfans out over the workspace. - Typechecking is a separate gate: vitest transpiles without type-checking, so a
test that exercises a type contract proves nothing unless
tscalso sees the file. Every buildtsconfig.jsonscopes the program tosrc, so every package carries atsconfig.typecheck.jsonthat adds its wholetests/tree back in; core's copy documents the trap thatexcludeis inherited from the extended config and filtersinclude, so it has to be restated.scripts/check-package-scripts.mjsfails the build when a workspace package declares notypecheckortestscript, which is how the gap that left ten packages silently unchecked is kept closed. - Three further guards run after the build, each for a defect class that shipped
green once:
scripts/check-package-artifacts.mjs(a manifest advertising a path the build did not leave on disk),scripts/check-embed-chunks.mjs(an embed bundle importing a chunk that was never emitted) andscripts/check-package-types.mjs(a shipped.d.tsthat exists but does not compile for a consumer). scripts/verify-browser.mjsdrives the built demo in a real headless Chrome through Playwright, covering what jsdom cannot: manifest failures, a mid-playback outage and automatic recovery, destroy-mid-append races against a locally generated HLS fixture, malformed live playlist refreshes, the shape of thewindow.ScarlettPlayerglobal the CDN embed publishes, control-bar reachability at phone widths (which needs a layout engine and a coarse pointer), and LL-HLS end to end against a rolling low-latency playlist assembled from the fixture's 0.5s part rendition. Fifty-nine checks across eight scenarios; CI runs it on pushes tomainonly, not on pull requests.scripts/hls-fixture.mjsgenerates both renditions the harness plays: 2s segments for everything else, and 0.5s parts for the LL scenario. The parts are real segments on keyframe boundaries rather than byte-range slices of the 2s ones, so four of them concatenate to exactly their parent segment. Slicing instead was tried and produces truncated access units that Chromium rejects withPIPELINE_ERROR_DECODEa few seconds into part-driven playback.
Browser support
Chrome and Edge 80+, Firefox 78+, Safari 14+, iOS Safari 14+, Android Chrome 90+. The same list is in the root README; keep the two in step.
See also
- Writing a plugin - events, state and controls
- Contributing - code standards, testing and review conventions
- README - installation, quick starts and the package table