Webcaster API reference & v5 → v6 migration
This page summarises the nanoStream Webcaster v6 API (SDK version 6.2.4) and shows how to migrate from version 5. The full generated reference, with every type, is at https://nanocosmos.github.io/webcaster/docs/. For working examples, see Webcaster guides.
Exports
Loading nanostream.webcaster.js with a script tag exposes window.WebcasterApiV6:
| Export | What it is |
|---|---|
Webcaster | The main class. One instance = one webcast. |
DeviceUtils | Static helpers to list and filter camera and microphone devices |
StreamUtils | Static helpers for MediaStream objects |
HelperUtils | Static helpers, for example kbps() and mbps() to convert to bits per second |
LogLevel, getLogger, getLogDumpData, overrideLoggerDefaults, overrideOnLogCallback | Logging. overrideOnLogCallback(fn) lets you capture SDK log lines, for example to show errors in your UI. |
VERSION, SHA | SDK version and build commit |
Config
Pass a config object to new Webcaster(config). All fields are optional, but you need streamName to broadcast. The config can't be changed after construction; create a new instance for a new config.
| Key | Type | Description |
|---|---|---|
streamName | string | Stream name to publish to (XXXXX-YYYYY). URL-encode any custom arguments yourself. |
serverUrl | string | WebRTC (WHIP) server. Default https://bintu-webrtc.nanocosmos.de/p/webrtc. |
ingestUrl | string | RTMP ingest the server forwards to. Default rtmp://bintu-stream.nanocosmos.de:1935/live. |
previewVideoElId | string | ID of the <video> element for startPreview() |
inputCfg | object | Input and encoding settings, see below |
reconnect | boolean or object | true for defaults, or { minDelaySec, maxDelaySec, maxRetries }. See Automatic reconnection. |
metrics | object | { accountId, accountKey } to send client metrics to nanoStream Analytics |
auth | object | { token }. Not active in the current version. |
inputCfg
| Key | Type | Description |
|---|---|---|
mediaStream | MediaStream | Your own stream (camera, screen, canvas). If set, mediaStreamCfg is ignored. |
mediaStreamCfg | object | Settings the SDK uses to create the stream itself, see below |
broadcastCfg | object | Encoding limits, see below |
muted | { audio?, video? } | Start muted |
inputCfg.mediaStreamCfg
| Key | Type | Description |
|---|---|---|
resolution | [width, height] | Requested resolution (an ideal value; the browser decides) |
maxFramerate | number | Maximum capture frame rate |
audioVideoOnly | 'audio' or 'video' | Audio-only or video-only ingest |
audioConstraints | object | autoGainControl, echoCancellation, noiseSuppression, channelCount |
audioDeviceId | string | deviceId of the microphone to use |
videoDeviceId | string | deviceId of the camera to use |
inputCfg.broadcastCfg
| Key | Type | Description |
|---|---|---|
maxVideoBitrateBps | number | Maximum video bitrate in bits per second |
maxAudioBitrateBps | number | Maximum audio bitrate in bits per second |
maxEncodingFramerate | number | Maximum encoded frame rate (not above maxFramerate) |
transcodeAudioBitrateBps | number | Server-side audio transcoding bitrate in bits per second |
Methods
All methods except the constructor need setup() first, unless noted.
| Method | Returns | Description |
|---|---|---|
new Webcaster(config) | Webcaster | Creates an instance. Nothing is captured yet. |
setup() | Promise<Config> | Creates the MediaStream if you didn't pass one, and resolves with the full config including defaults. Must be called before anything else. |
startPreview(videoElId?) | void | Attaches the stream to a <video> element. Uses previewVideoElId if you pass no ID. |
startBroadcast() | Promise<void> | Starts the webcast (WHIP offer/answer exchange). |
stopBroadcast() | Promise<void> | Stops the webcast. Keeps the MediaStream, so you can start again. |
recover(disposeMediaStream = false) | Promise<void> | Resets the instance after a failure so you can start a new broadcast with the same config. With true, also stops the current tracks (don't do that with a stream you passed in yourself). |
dispose(withMediaStream = false) | Promise<void> | Full stop: ends any broadcast and resets to before setup(). With true, also stops the media tracks. |
setMuted({ audio?, video? }) | void | Mutes or unmutes audio and/or video. Can be called before setup(). |
isMuted() | { audio, video } | Current mute state |
sendMetadata(handlerName, data) | Promise<void> | Sends live metadata. handlerName is 'onMetaData' or 'onCuePoint'; data has a maximum depth of 6. |
getUpstreamStatus() | UpstreamConnectionStatus | Connection state. Can be called any time. |
getMediaStreamSettings() | MediaStreamSettings | Settings actually applied to the audio and video tracks |
getConfiguredConstraints() | MediaStreamConstraints or null | The constraints the SDK built from your config |
UpstreamConnectionStatus
| Field | Type |
|---|---|
connectionState | RTCPeerConnectionState or null |
iceState | RTCIceConnectionState or null |
gatheringState | RTCIceGatheringState or null |
localDescription | RTCSessionDescription or null |
remoteDescription | RTCSessionDescription or null |
Callbacks
Assign your own functions to these properties:
| Callback | Argument | Called when |
|---|---|---|
onStateChange | none | The Webcaster state changes. Read getUpstreamStatus() inside. |
onConnectionStateChange | RTCPeerConnectionState | The WebRTC connection state changes (connecting, connected, failed, …) |
onReconnectionStateChange | ReconnectionState | Automatic reconnection changes state: idle, reconnecting, failed |
onMetrics | metrics object | At an interval during a broadcast, and immediately for errors |
onError | WebcasterError | An error occurs |
client.onError = (err) => console.error(err.code, err.message);
client.onStateChange = () => console.log(client.getUpstreamStatus().connectionState);
client.onReconnectionStateChange = (state) => console.log('reconnect:', state);
client.onMetrics = (metrics) => console.log(metrics);
Helpers
| Helper | Description |
|---|---|
DeviceUtils.getAvailableMediaDevices(audioVideoOnly?) | Promise<MediaDeviceInfo[]> of the available devices. 'audio' or 'video' restricts the permission check to that kind. |
DeviceUtils.filterDevices(devices, kinds?, groupId?, deviceId?) | Filters a device list. kinds defaults to ['audioinput', 'videoinput']. |
DeviceUtils.getDevicePermissions(devices) | Checks camera and microphone permissions with the Permissions API (Chromium on desktop and Android) |
DeviceUtils.isSupported(method) | Whether a MediaDevices method exists in this browser |
StreamUtils.hasAudio(stream), hasVideo(stream) | Whether a MediaStream has audio or video tracks |
StreamUtils.disposeStream(stream) | Stops all tracks of a stream |
HelperUtils.kbps(n), HelperUtils.mbps(n) | Convert kbit/s or Mbit/s to bits per second |
Error codes
Every error is a WebcasterError (or a subclass) with message and a numeric code. Rejected promises and onError both carry it.
| Code | Name | Meaning |
|---|---|---|
| 2001 | MStreamAlreadyExists | MediaStream already exists, for example setup() called twice |
| 2002 | MStreamNotFound | No MediaStream yet; setup() not called |
| 2003 | MStreamNotCreated | Creating the MediaStream failed. See the message. |
| 4000 | General | Unrecognised error |
| 4001 | GeneralSetupNotCalled | setup() hasn't been called |
| 4002 | GeneralBroadcastNotStarted | startBroadcast() hasn't been called |
| 4003 | GeneralRecoveryFailed | Recovery failed |
| 4004 | GeneralLoggerSetupFailed | Logger setup failed |
| 5001 | BroadcastPCNotFound | No peer connection yet, for example stopBroadcast() or dispose() called twice |
| 5002 | BroadcastPCAlreadyExists | Peer connection exists, for example startBroadcast() called twice |
| 5003 | BroadcastPCAddTransceiverFailed | Adding a transceiver failed |
| 5004 | BroadcastCreateOfferFailed | Creating the offer failed, or the SDP was empty |
| 5005 | BroadcastSetAnswerFailed | Setting the answer failed |
| 5006 | BroadcastApplyConstraintsFailed | Applying constraints to a sender failed. Check broadcastCfg. |
| 6001 | MDevicesMethodNotSupported | A MediaDevices method isn't available in this browser |
| 6002 | MDevicesKindNotSupported | Media device kind not supported |
| 6003 | MDevicesPermissionQueryFailed | Permission query for devices failed |
| 7000 | ValidationError | The config failed validation. The message names the field. |
| 8001 | MetricsParseUserAgentFailed | Parsing the user agent for metrics failed |
| 8002 | MetricsInvalidTrackKind | Track kind for stats is not audio or video |
| 8003 | MetricsInitStatsCollectFailed | Starting stats collection failed |
| 8004 | MetricsStopStatsCollectFailed | Stopping stats collection failed |
| 10001 | ServerMalformedResponse | Server response missing fields or with empty SDP |
| 10002 | ServerCreateResourceFailed | Creating the resource on the server failed |
| 10003 | ServerRequestFailed | Server error (HTTP 5xx). See the error's message and metadata. |
| 11001 | ClientRequestFailed | Server not reachable, or HTTP 4xx |
| 11002 | ClientResourceAlreadyExists | A previous broadcast wasn't cleaned up |
| 11003 | ClientResourceNotFound | Resource doesn't exist, for example startBroadcast() not called yet |
| 11004 | ClientRequestPending | A start or stop request is still pending |
Migrate from v5 to v6
Version 6 replaces version 5, which is legacy. Reasons to migrate:
- More reliable stream starts. v6 negotiates the connection with the standard WHIP protocol instead of the proprietary WebSocket protocol of v5.
- Less code. A flatter config and promise-based methods.
- Easier custom sources. Pass any
MediaStream(screen, canvas, virtual devices). - TypeScript definitions ship with the SDK.
- New features such as automatic reconnection (6.1.0) arrive in v6 only.
What changes
| v5 | v6 |
|---|---|
new RtcUser() | new WebcasterApiV6.Webcaster(config) |
Event listeners: rtcUser.on('StartBroadcastSuccess', …), 'StartBroadcastError', … | Methods return promises; use await with try/catch |
signIn({ server, … }) before broadcasting | No sign-in. Set serverUrl (or use the default). |
startPreview({ videoDeviceConfig, audioDeviceConfig, elementId }) | Config in inputCfg.mediaStreamCfg, then setup() and startPreview(videoElId) |
startBroadcast({ … rtmp url, stream name … }) | streamName and ingestUrl in the config, then startBroadcast() |
getDevices() + ReceivedDeviceList event | DeviceUtils.getAvailableMediaDevices() |
setVideoDevice() / setAudioDevice() | videoDeviceId / audioDeviceId in mediaStreamCfg |
videoDeviceConfig: { source: 'screen' } | Pass a getDisplayMedia() stream in inputCfg.mediaStream |
injectExternalMediaStream() / setMediaStream() | inputCfg.mediaStream |
muteAudio() / muteVideo() | setMuted({ audio, video }) |
sendMetaData(handlerName, values) | sendMetadata(handlerName, data) |
ReceivedWebRTCStats event, enableStats() | onMetrics callback |
JWT ingest tokens in signIn() / startBroadcast() | Not available in v6 yet (see Secure ingest) |
From events to promises
// v5: event-based
rtcUser.on('StartBroadcastSuccess', () => console.log('Broadcast started'));
rtcUser.on('StartBroadcastError', (event) => console.error('Error:', event));
rtcUser.startBroadcast(broadcastConfig);
// v6: promise-based
try {
await client.startBroadcast();
console.log('Broadcast started');
} catch (error) {
console.error('Error:', error.code, error.message);
}
Step 1: Replace the library
Replace the v5 script with the v6 file from https://github.com/nanocosmos/webcaster and add a preview element:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="dist/nanostream.webcaster.js"></script>
</head>
<body>
{/* video element for previewing your MediaStream */}
<video id="preview" muted autoplay playsinline></video>
</body>
</html>
Step 2: Rewrite the initialisation
const { Webcaster, HelperUtils } = window.WebcasterApiV6;
let client;
const initConfig = {
streamName: '<YOUR_STREAM_NAME>',
serverUrl: 'https://bintu-webrtc.nanocosmos.de/p/webrtc',
ingestUrl: 'rtmp://bintu-stream.nanocosmos.de:1935/live',
previewVideoElId: 'preview',
inputCfg: {
// Leave out mediaStream to let the SDK create one from mediaStreamCfg
mediaStreamCfg: {
maxFramerate: 30,
resolution: [1280, 720],
audioConstraints: {
autoGainControl: true,
channelCount: 2,
echoCancellation: true,
noiseSuppression: true
}
},
broadcastCfg: {
transcodeAudioBitrateBps: HelperUtils.kbps(128),
maxAudioBitrateBps: HelperUtils.kbps(128),
maxVideoBitrateBps: HelperUtils.kbps(2000),
maxEncodingFramerate: 30
}
}
};
// Run after the DOM is ready, so the preview element exists
document.addEventListener('DOMContentLoaded', async () => {
client = new Webcaster(initConfig);
try {
await client.setup();
console.log('Webcaster.setup done');
} catch (err) {
console.error('Webcaster.setup failed:', err);
}
});
Step 3: Select devices (optional)
Replace v5 device selection with DeviceUtils and pass the IDs in the config:
const { Webcaster, HelperUtils, DeviceUtils } = window.WebcasterApiV6;
let client;
document.addEventListener('DOMContentLoaded', async () => {
const devices = await DeviceUtils.getAvailableMediaDevices();
const videoDevices = DeviceUtils.filterDevices(devices, ['videoinput']);
const audioDevices = DeviceUtils.filterDevices(devices, ['audioinput']);
client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
previewVideoElId: 'preview',
inputCfg: {
mediaStreamCfg: {
videoDeviceId: videoDevices[0]?.deviceId, // first camera
audioDeviceId: audioDevices[0]?.deviceId, // first microphone
maxFramerate: 30,
resolution: [1280, 720]
},
broadcastCfg: {
maxVideoBitrateBps: HelperUtils.kbps(2000),
maxAudioBitrateBps: HelperUtils.kbps(128)
}
}
});
await client.setup();
});
Step 4: Pass your own MediaStream (optional)
Replaces injectExternalMediaStream() / setMediaStream() and v5 screen capture:
const { Webcaster, HelperUtils } = window.WebcasterApiV6;
let client;
document.addEventListener('DOMContentLoaded', async () => {
let stream;
try {
// Camera and microphone:
stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
// Or a screen share with microphone audio:
// const mic = await navigator.mediaDevices.getUserMedia({ audio: true });
// const screen = await navigator.mediaDevices.getDisplayMedia({ video: true });
// stream = new MediaStream([screen.getVideoTracks()[0], mic.getAudioTracks()[0]]);
} catch (error) {
console.error('Error creating stream:', error);
return;
}
client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
previewVideoElId: 'preview',
inputCfg: {
mediaStream: stream,
broadcastCfg: {
transcodeAudioBitrateBps: HelperUtils.kbps(128),
maxAudioBitrateBps: HelperUtils.kbps(128),
maxVideoBitrateBps: HelperUtils.kbps(2000),
maxEncodingFramerate: 30
}
}
});
await client.setup();
});
Step 5: Connect your UI
<button id="btn-preview">Start preview</button>
<button id="btn-start">Start broadcast</button>
<button id="btn-stop">Stop broadcast</button>
<button id="btn-mute">Mute</button>
<button id="btn-recover">Recover</button>
<button id="btn-dispose">Dispose</button>
function on(id, handler) {
document.getElementById(id).addEventListener('click', async () => {
if (!client) {
alert('Create the Webcaster instance first');
return;
}
try {
await handler();
} catch (err) {
console.error(`${id} failed:`, err);
}
});
}
on('btn-preview', () => client.startPreview());
on('btn-start', () => client.startBroadcast());
on('btn-stop', () => client.stopBroadcast());
on('btn-mute', () => client.setMuted({ audio: true, video: true }));
on('btn-recover', () => client.recover());
on('btn-dispose', async () => {
await client.dispose();
client = null;
});
Step 6: Update error handling and state events
Replace your v5 error and status event listeners:
client.onError = (err) => {
console.error('Webcaster.onError:', err.code, err.message);
};
client.onStateChange = () => {
console.log('Webcaster.onStateChange:', client.getUpstreamStatus());
};
client.onMetrics = (metrics) => {
console.log('Webcaster.onMetrics:', metrics);
};
Step 7: Test
Test the whole flow in every browser you support: permissions, preview, start, stop, mute, network loss (with reconnect on) and dispose. The main sample lets you compare behaviour with a known-good page.
Release history
| Version | Date | Highlights |
|---|---|---|
| 6.2.4 | 2026-08-26 | Audio-only and video-only broadcasts only request the permission they need; device listing no longer depends on the other device kind. |
| 6.2.0 | 2024-07-15 | More error codes, better session metrics; fixes for low resolutions in Chrome and for metrics sent after a failure. |
| 6.1.0 | 2024-04-10 | Automatic reconnection. Fixes: dispose() could leave a dirty state; muted tracks are no longer re-enabled; isMuted() reports correctly. |
| 6.0.2 | 2023-12-04 | First public v6 release |
For all products, see Release notes.
Next steps
- nanoStream Webcaster: getting started
- Webcaster guides
- Legacy & retired docs: v5 documentation