Skip to main content

Events & error codes

The nanoStream Player tells your application what is happening through events. Use them to drive your UI, collect statistics and decide how to react to errors. This page lists every event, the player states and pause reasons, all error codes, and a tested retry pattern.

Register events​

Pass handlers in config.events when you call setup():

var config = {
source: { /* ... */ },
events: {
onReady: function (e) { console.log("ready, player " + e.version); },
onPlay: function (e) { console.log("startup took " + e.data.stats.playing + " ms"); },
onPause: function (e) { console.log("paused: " + e.data.reason); },
onError: function (e) { console.log(e.data.code + ": " + e.data.message); },
onStats: function (e) { console.log("latency " + e.data.stats.buffer.delay.current); }
}
};
player.setup(config);
info

Register events in config.events, not later inside setup().then(). The player can fire onReady, onStreamInfo and onPlay before the then callback runs, so late handlers miss them.

Every event object has these fields:

FieldDescription
nameEvent name
playerID of the player div
idUnique ID of the player instance
versionPlayer version
statePlayer state (see Player states)
dataEvent-specific data (below)

Events​

Lifecycle and playback​

EventFires whendata
onReadySetup succeededconfig
onLoadingPlayback is about to start, or restartsconnectDelay: ms until connecting; 0 unless a reconnect is coming
onPlayPlayback startedstats: startup timings in ms relative to the play call: connecting (always 0), connected, firstFragmentReceived, firstFrameRendered, playable, playing (total startup time)
onPausePlayback pausedreason: see Pause reasons
onStartBufferingPlaying, but no media available—
onStopBufferingPlayback resumed after buffering—
onDestroyThe player was destroyed—

Stream information and statistics​

EventFires whendata
onStreamInfoStream details are known, right before playback startsstreamInfo: url, rtmp.url, rtmp.streamname, haveAudio, haveVideo, audioInfo (bitsPerSample, sampleRate, channels), videoInfo (width, height, frameRate)
onStreamInfoUpdateThe stream format changed during playbackstreamInfo (as above)
onStatsNew statistics measuredstats (below)
onMetaDataIn-stream metadata received (needs playback.metadata: true)handlerName, message, streamTime
onServerInfoH5Live server info availableserverInfo: applicationServerName, applicationServerVersion, hostname

onStats → data.stats:

FieldDescription
currentTimeCurrent playback time
playout.start / playout.endPlayable range
buffer.start / buffer.endBuffered range
buffer.delay.current / .avg / .min / .maxBuffer delay; avg/min/max over the last second
bitrate.current / .avg / .min / .maxBitrate in bit/s; avg/min/max over the last 10 s. 0 if unavailable; not available for HLS playback.
framerate.current / .avg / .min / .maxNetwork frame rate; not available for HLS playback
playbackrate.current / .avg / .min / .maxVideo playback rate (latency control)
buffergoal.base / .real / .min / .maxBuffer goal values used by latency control
quality.droppedVideoFrames / droppedVideoFramesCurrentDropped frames, total and in the last second
quality.corruptedVideoFrames / corruptedVideoFramesCurrentCorrupted frames, total and in the last second
quality.totalVideoFramesTotal frames since the video element was created
quality.creationTimems from navigation start to video element creation
quality.sourceBufferDetached1 if the media source buffer was detached and recovered since the last tick

Use onStats for live latency, bitrate and buffer readouts instead of polling.

Audio and display​

EventFires whendata
onMute / onUnmute / onVolumeChangeAudio state changedvolume (0.0–1.0)
onFullscreenChangeFullscreen entered or leftentered (boolean)
onActiveVideoElementChangeA video element was created or became activeactiveVideoElement, videoElementList (two elements on iOS)

Switching and source updates​

EventFires when
onSwitchStreamInitA switch started (manual or ABR)
onSwitchStreamSuccessThe switch completed
onSwitchStreamFailThe switch failed (data.code, data.message)
onSwitchStreamAbortThe switch was aborted (data.reason)
onUpdateSourceInitupdateSource() started
onUpdateSourceSuccessThe new source plays
onUpdateSourceFailThe update failed (data.code, data.message)
onUpdateSourceAbortThe update was aborted (data.reason)

Switch and update events carry data.source, data.entry, data.rule, data.options, data.tag (your options.switch.tag), and data.count / data.id to pair the start and completion events. data.type is up or down for ABR switches, direct for switchStream(), and update for updateSource(). Abort reasons: equalsource, superseded, frequency.

Warnings and errors​

EventFires whendata
onWarningSomething is unexpected but playback works, for example a media error recoverymessage
onErrorAn error occurredcode, message, and for startup errors playback and state (below)

Startup errors (since 4.28.0) are errors during loading or the first 30 seconds of playback. Their onError data adds:

FieldDescription
playback.bufferDelayCurrentBuffer delay at the time of the error
playback.bitrateCurrentBitrate in bit/s at the time of the error
playback.framerateCurrentFrame rate at the time of the error
state.connected, state.firstFragmentReceived, state.firstFrameRendered, state.playable, state.playingms since load start for each startup step reached (optional)
state.errorms since load start when the error occurred

There is no separate event for an offline or unknown stream. It arrives in onError: 2001 (stream not found), 2002 (media not available) or 2003 (not enough data), or a network error in the 4000 range. onPause then fires with reason streamnotfound for the loading timeout.

Player states​

ValueState
1UNINITIALIZED
2IDLE
3READY
4LOADING
5PLAYING
6PAUSED
7BUFFERING
8UNKNOWN
9PLAYBACK_NOT_STARTED
10PLAYBACK_SUSPENDED
11PAUSING
12PLAYBACK_ERROR
13RECONNECTION_IMMINENT
14CONNECTION_ERROR
15DESTROYING
16PLAYBACK_RESTARTING
17VISIBILITY_HIDDEN
18NOT_ENOUGH_DATA
19SOURCE_STREAM_STOPPED

Pause reasons​

onPause → data.reason:

ReasonMeaning
normalPaused by the user or by pause()
bufferBuffering timeout: the stream stopped or the buffer ran empty
connectioncloseThe network connection closed
servernotfoundThe H5Live server wasn't found
streamnotfoundLoading timeout: the stream wasn't found
notenoughdataLoading timeout: connected, but not enough data to start
sourcestreamstoppedThe source stream stopped
interactionrequiredAutoplay was denied; a user gesture is needed
playbacksuspendedPlayback was suspended externally (for example the app went to the background)
playbackerrorA playback error occurred
reconnectionimminentThe connection closed and the player is about to reconnect
playbackrestartPaused for updateSource(); restarts immediately
visibilityhiddenThe player wasn't visible when loading started
destroyThe player is being destroyed
note

pause() stops rendering but keeps the connection open, so a paused viewer still counts as connected in analytics. Only destroy() ends the session.

Error codes​

RangeGroup
1000–1999Player errors
2000–2999Stream errors
3000–3999Media errors
4000–4899Network errors
4900–4999Security errors
5000–5999Setup errors (5100–5199 REST API lookup, 5200–5299 metrics config)

Player errors (1xxx)​

CodeMessageWhat to do
1001No rtmp url setFix the source config
1002No server setFix the source config
1003Could not play because player has not been configuredCall setup() first
1004Could not pause because player was not in playing state beforeNo action
1005Playback must be initialized by user gestureAutoplay blocked or iOS Low Power Mode. Show a "tap to play" button.
1006Buffer config is invalidFix tweaks.buffer
1007Playback suspended by external reasonThe mobile browser or OS stopped playback (tab switch, call, lock). Call play() when the page is visible again.
1008Playback erroriOS. Recovered automatically (media error recovery).
1009Playback failed because the player was in visibility state 'hidden' at load startStarted in a background tab. Call play() on visibilitychange.
1010The given stream entry index is not validCheck the switchStream() index

Stream errors (2xxx)​

CodeMessageMeaning
2001The requested stream can not be foundNo stream info or media received within timeouts.loading. Is the stream live? Right playout name?
2002No media availableWas playing, then media stopped arriving (timeouts.buffering)
2003Not enough media data receivedStream info received but no media
2004The source stream has been stoppedThe stream was unpublished while playing
2011–2014Metadata errorsWrong index, invalid JSON, no start index, or overlapping metadata. Playback continues.

Media errors (3xxx)​

CodeMessage
3001A fetching process of the media aborted by user
3002An error occurred when downloading media
3003An error occurred when decoding media (auto-recovered)
3004The received audio/video is not supported
3005An error occurred while hls playback when decoding video (auto-recovered)
3100The media source extension changed the state to 'ended' (auto-recovered; not for HLS)
3101An error occurred while buffering on hls playback (auto-recovered)
3102Buffer range is higher than allowed on hls playback
3200An unspecific media error occurred

Network errors (40xx–45xx)​

CodeMessage
4001Could not establish connection. Maybe wrong protocol or path.
4002Connection error
4003Maximum number of reconnection tries reached
4004Reconnection configuration invalid
4005The requested source stream has been stopped
4006The source request was aborted by timeout (updateSource / switchStream)
4101Endpoint going away (server down or page navigated away)
4102Protocol error. Reconnect possible.
4103Unacceptable data type. Reconnect possible.
4104Reserved
4105No status code present. Reconnect possible.
4106Maybe no network, wrong url or server down. Reconnect possible.
4107Inconsistent message data
4108Policy violation. Reconnect possible.
4109Message too big. Reconnect possible.
4110Required extension not negotiated
4111Unexpected server condition. Reconnect possible.
4115TLS handshake failed. Reconnect possible.
4400Bad request. Stream parameters missing or malformed.
4403Access denied. The authentication token is missing or invalid.
4500Internal server error. Reconnect possible.
4503Service unavailable. Reconnect possible.

Security errors (49xx)​

CodeMessageWhat to do
4900The security service has been rejected due an internal server errorRetry later; contact support if it persists
4901The security service denied access. The authentication token is invalid.Get a new, valid token from your backend
4903The url is expired or a token parameter is missingToken expired or incomplete. Get a new token.
4904The security service can not be foundContact support

See Playback tokens.

Setup errors (5xxx)​

CodeMessageWhat to do
5001An exception was thrown during setupUsually an undefined error in your own code inside the setup promise or an event handler
5002This browser does not fully support HTML5 and H5LiveThe browser lacks a required playback technology. The message text lists older browser versions; ignore them. See Supported browsers & devices.
5003A forced tech is not supported by your browserRemove the forced playback technology
5004The players source configuration is malformed or missingCheck source, group.id or rtmp.streamname
5005The rtmp configuration is missing or incompleteAdd the RTMP URL and stream name, or use defaults.service
5006A security token is requiredAdd security.jwtoken
5007The websocket server configuration is missingAdd h5live.server.websocket or use defaults.service
5008The hls server configuration is missingAdd h5live.server.hls or use defaults.service
5009The websocket server configuration for metadata is missingAdd the WebSocket server
5010Could not embed playerCheck the player div
5101Could not find bintu stream. The stream is not live.Wait until the stream is live, then call setup() again
5102No bintu stream id passedAdd bintu.streamid or group.id
5103Bintu service rejectedCheck the ID and the API URL
5201–5208Metrics configuration errorsFix the metrics block (missing object, wrong type, empty, credentials missing, customField index outside 1–10, invalid property)

Handle errors and retry​

The player already recovers from many problems by itself before your code sees an error:

  • Media errors 1008, 3003, 3005, 3100, 3101: automatic recovery (playback.mediaErrorRecoveries).
  • Network errors 4102, 4103, 4105, 4106, 4107, 4108, 4109, 4111, 4115, 4500, 4503: automatic reconnect (playback.reconnect), on all platforms except iOS.

So decide what to do in three buckets:

BucketCodesAction
Handled by the playerSee aboveDon't retry yourself
Don't retry1005, 1007, 1009 (autoplay, background, visibility); 4900–4999 (security); 5001–5010 (setup)Wait for a user gesture or visibility, fetch a new token, or fix the config
Retry with limitsEverything else, for example 2001–2004Call play(), cap the number of attempts, and increase the delay between them

Recommended flow: store the error in onError, decide in onPause (it fires right after the error), and reset your counter in onPlay, onSwitchStreamSuccess and onUpdateSourceSuccess.

var lastError = null;
var attempts = 0, maxAttempts = 10;

var noRetry = [1005, 1007, 1008, 1009, 3001, 3002, 3003, 3004, 3005, 3100, 3101, 3200, 4003];

function shouldRetry(code) {
if (noRetry.indexOf(code) !== -1) return false;
if (code >= 4001 && code <= 4999) return false; // network (handled by reconnect) and security
if (code >= 5001 && code <= 5010) return false; // setup
return true;
}

config.events = {
onPlay: function () { attempts = 0; },
onSwitchStreamSuccess: function () { attempts = 0; },
onUpdateSourceSuccess: function () { attempts = 0; },
onError: function (e) { lastError = e.data; },
onPause: function (e) {
if (lastError && e.data.reason !== "normal" && shouldRetry(lastError.code)) {
if (attempts < maxAttempts) {
attempts++;
setTimeout(function () { player.play(); }, attempts * 1000); // growing delay
} else {
showMessage("Stream not available. Try again later.");
}
}
lastError = null;
}
};

The example treats all of 4001–4999 as "don't replay" to stay simple. Some of these codes only arrive after the player's own reconnect attempts have given up: 4001, 4002, 4003, 4005, 4006, 4101–4115, 4201, 4500 and 4503. You can replay those after a longer backoff. Don't replay 4400, 4401 or 4900–4904: they are security errors, so get a new token first.

Next steps​