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);
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:
| Field | Description |
|---|
name | Event name |
player | ID of the player div |
id | Unique ID of the player instance |
version | Player version |
state | Player state (see Player states) |
data | Event-specific data (below) |
Events
Lifecycle and playback
| Event | Fires when | data |
|---|
onReady | Setup succeeded | config |
onLoading | Playback is about to start, or restarts | connectDelay: ms until connecting; 0 unless a reconnect is coming |
onPlay | Playback started | stats: startup timings in ms relative to the play call: connecting (always 0), connected, firstFragmentReceived, firstFrameRendered, playable, playing (total startup time) |
onPause | Playback paused | reason: see Pause reasons |
onStartBuffering | Playing, but no media available | — |
onStopBuffering | Playback resumed after buffering | — |
onDestroy | The player was destroyed | — |
| Event | Fires when | data |
|---|
onStreamInfo | Stream details are known, right before playback starts | streamInfo: url, rtmp.url, rtmp.streamname, haveAudio, haveVideo, audioInfo (bitsPerSample, sampleRate, channels), videoInfo (width, height, frameRate) |
onStreamInfoUpdate | The stream format changed during playback | streamInfo (as above) |
onStats | New statistics measured | stats (below) |
onMetaData | In-stream metadata received (needs playback.metadata: true) | handlerName, message, streamTime |
onServerInfo | H5Live server info available | serverInfo: applicationServerName, applicationServerVersion, hostname |
onStats → data.stats:
| Field | Description |
|---|
currentTime | Current playback time |
playout.start / playout.end | Playable range |
buffer.start / buffer.end | Buffered range |
buffer.delay.current / .avg / .min / .max | Buffer delay; avg/min/max over the last second |
bitrate.current / .avg / .min / .max | Bitrate in bit/s; avg/min/max over the last 10 s. 0 if unavailable; not available for HLS playback. |
framerate.current / .avg / .min / .max | Network frame rate; not available for HLS playback |
playbackrate.current / .avg / .min / .max | Video playback rate (latency control) |
buffergoal.base / .real / .min / .max | Buffer goal values used by latency control |
quality.droppedVideoFrames / droppedVideoFramesCurrent | Dropped frames, total and in the last second |
quality.corruptedVideoFrames / corruptedVideoFramesCurrent | Corrupted frames, total and in the last second |
quality.totalVideoFrames | Total frames since the video element was created |
quality.creationTime | ms from navigation start to video element creation |
quality.sourceBufferDetached | 1 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
| Event | Fires when | data |
|---|
onMute / onUnmute / onVolumeChange | Audio state changed | volume (0.0–1.0) |
onFullscreenChange | Fullscreen entered or left | entered (boolean) |
onActiveVideoElementChange | A video element was created or became active | activeVideoElement, videoElementList (two elements on iOS) |
Switching and source updates
| Event | Fires when |
|---|
onSwitchStreamInit | A switch started (manual or ABR) |
onSwitchStreamSuccess | The switch completed |
onSwitchStreamFail | The switch failed (data.code, data.message) |
onSwitchStreamAbort | The switch was aborted (data.reason) |
onUpdateSourceInit | updateSource() started |
onUpdateSourceSuccess | The new source plays |
onUpdateSourceFail | The update failed (data.code, data.message) |
onUpdateSourceAbort | The 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
| Event | Fires when | data |
|---|
onWarning | Something is unexpected but playback works, for example a media error recovery | message |
onError | An error occurred | code, 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:
| Field | Description |
|---|
playback.bufferDelayCurrent | Buffer delay at the time of the error |
playback.bitrateCurrent | Bitrate in bit/s at the time of the error |
playback.framerateCurrent | Frame rate at the time of the error |
state.connected, state.firstFragmentReceived, state.firstFrameRendered, state.playable, state.playing | ms since load start for each startup step reached (optional) |
state.error | ms 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
| Value | State |
|---|
| 1 | UNINITIALIZED |
| 2 | IDLE |
| 3 | READY |
| 4 | LOADING |
| 5 | PLAYING |
| 6 | PAUSED |
| 7 | BUFFERING |
| 8 | UNKNOWN |
| 9 | PLAYBACK_NOT_STARTED |
| 10 | PLAYBACK_SUSPENDED |
| 11 | PAUSING |
| 12 | PLAYBACK_ERROR |
| 13 | RECONNECTION_IMMINENT |
| 14 | CONNECTION_ERROR |
| 15 | DESTROYING |
| 16 | PLAYBACK_RESTARTING |
| 17 | VISIBILITY_HIDDEN |
| 18 | NOT_ENOUGH_DATA |
| 19 | SOURCE_STREAM_STOPPED |
Pause reasons
onPause → data.reason:
| Reason | Meaning |
|---|
normal | Paused by the user or by pause() |
buffer | Buffering timeout: the stream stopped or the buffer ran empty |
connectionclose | The network connection closed |
servernotfound | The H5Live server wasn't found |
streamnotfound | Loading timeout: the stream wasn't found |
notenoughdata | Loading timeout: connected, but not enough data to start |
sourcestreamstopped | The source stream stopped |
interactionrequired | Autoplay was denied; a user gesture is needed |
playbacksuspended | Playback was suspended externally (for example the app went to the background) |
playbackerror | A playback error occurred |
reconnectionimminent | The connection closed and the player is about to reconnect |
playbackrestart | Paused for updateSource(); restarts immediately |
visibilityhidden | The player wasn't visible when loading started |
destroy | The player is being destroyed |
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
| Range | Group |
|---|
| 1000–1999 | Player errors |
| 2000–2999 | Stream errors |
| 3000–3999 | Media errors |
| 4000–4899 | Network errors |
| 4900–4999 | Security errors |
| 5000–5999 | Setup errors (5100–5199 REST API lookup, 5200–5299 metrics config) |
Player errors (1xxx)
| Code | Message | What to do |
|---|
| 1001 | No rtmp url set | Fix the source config |
| 1002 | No server set | Fix the source config |
| 1003 | Could not play because player has not been configured | Call setup() first |
| 1004 | Could not pause because player was not in playing state before | No action |
| 1005 | Playback must be initialized by user gesture | Autoplay blocked or iOS Low Power Mode. Show a "tap to play" button. |
| 1006 | Buffer config is invalid | Fix tweaks.buffer |
| 1007 | Playback suspended by external reason | The mobile browser or OS stopped playback (tab switch, call, lock). Call play() when the page is visible again. |
| 1008 | Playback error | iOS. Recovered automatically (media error recovery). |
| 1009 | Playback failed because the player was in visibility state 'hidden' at load start | Started in a background tab. Call play() on visibilitychange. |
| 1010 | The given stream entry index is not valid | Check the switchStream() index |
Stream errors (2xxx)
| Code | Message | Meaning |
|---|
| 2001 | The requested stream can not be found | No stream info or media received within timeouts.loading. Is the stream live? Right playout name? |
| 2002 | No media available | Was playing, then media stopped arriving (timeouts.buffering) |
| 2003 | Not enough media data received | Stream info received but no media |
| 2004 | The source stream has been stopped | The stream was unpublished while playing |
| 2011–2014 | Metadata errors | Wrong index, invalid JSON, no start index, or overlapping metadata. Playback continues. |
| Code | Message |
|---|
| 3001 | A fetching process of the media aborted by user |
| 3002 | An error occurred when downloading media |
| 3003 | An error occurred when decoding media (auto-recovered) |
| 3004 | The received audio/video is not supported |
| 3005 | An error occurred while hls playback when decoding video (auto-recovered) |
| 3100 | The media source extension changed the state to 'ended' (auto-recovered; not for HLS) |
| 3101 | An error occurred while buffering on hls playback (auto-recovered) |
| 3102 | Buffer range is higher than allowed on hls playback |
| 3200 | An unspecific media error occurred |
Network errors (40xx–45xx)
| Code | Message |
|---|
| 4001 | Could not establish connection. Maybe wrong protocol or path. |
| 4002 | Connection error |
| 4003 | Maximum number of reconnection tries reached |
| 4004 | Reconnection configuration invalid |
| 4005 | The requested source stream has been stopped |
| 4006 | The source request was aborted by timeout (updateSource / switchStream) |
| 4101 | Endpoint going away (server down or page navigated away) |
| 4102 | Protocol error. Reconnect possible. |
| 4103 | Unacceptable data type. Reconnect possible. |
| 4104 | Reserved |
| 4105 | No status code present. Reconnect possible. |
| 4106 | Maybe no network, wrong url or server down. Reconnect possible. |
| 4107 | Inconsistent message data |
| 4108 | Policy violation. Reconnect possible. |
| 4109 | Message too big. Reconnect possible. |
| 4110 | Required extension not negotiated |
| 4111 | Unexpected server condition. Reconnect possible. |
| 4115 | TLS handshake failed. Reconnect possible. |
| 4400 | Bad request. Stream parameters missing or malformed. |
| 4403 | Access denied. The authentication token is missing or invalid. |
| 4500 | Internal server error. Reconnect possible. |
| 4503 | Service unavailable. Reconnect possible. |
Security errors (49xx)
| Code | Message | What to do |
|---|
| 4900 | The security service has been rejected due an internal server error | Retry later; contact support if it persists |
| 4901 | The security service denied access. The authentication token is invalid. | Get a new, valid token from your backend |
| 4903 | The url is expired or a token parameter is missing | Token expired or incomplete. Get a new token. |
| 4904 | The security service can not be found | Contact support |
See Playback tokens.
Setup errors (5xxx)
| Code | Message | What to do |
|---|
| 5001 | An exception was thrown during setup | Usually an undefined error in your own code inside the setup promise or an event handler |
| 5002 | This browser does not fully support HTML5 and H5Live | The browser lacks a required playback technology. The message text lists older browser versions; ignore them. See Supported browsers & devices. |
| 5003 | A forced tech is not supported by your browser | Remove the forced playback technology |
| 5004 | The players source configuration is malformed or missing | Check source, group.id or rtmp.streamname |
| 5005 | The rtmp configuration is missing or incomplete | Add the RTMP URL and stream name, or use defaults.service |
| 5006 | A security token is required | Add security.jwtoken |
| 5007 | The websocket server configuration is missing | Add h5live.server.websocket or use defaults.service |
| 5008 | The hls server configuration is missing | Add h5live.server.hls or use defaults.service |
| 5009 | The websocket server configuration for metadata is missing | Add the WebSocket server |
| 5010 | Could not embed player | Check the player div |
| 5101 | Could not find bintu stream. The stream is not live. | Wait until the stream is live, then call setup() again |
| 5102 | No bintu stream id passed | Add bintu.streamid or group.id |
| 5103 | Bintu service rejected | Check the ID and the API URL |
| 5201–5208 | Metrics configuration errors | Fix 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:
| Bucket | Codes | Action |
|---|
| Handled by the player | See above | Don't retry yourself |
| Don't retry | 1005, 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 limits | Everything else, for example 2001–2004 | Call 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;
if (code >= 5001 && code <= 5010) return false;
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);
} 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