Skip to main content

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:

ExportWhat it is
WebcasterThe main class. One instance = one webcast.
DeviceUtilsStatic helpers to list and filter camera and microphone devices
StreamUtilsStatic helpers for MediaStream objects
HelperUtilsStatic helpers, for example kbps() and mbps() to convert to bits per second
LogLevel, getLogger, getLogDumpData, overrideLoggerDefaults, overrideOnLogCallbackLogging. overrideOnLogCallback(fn) lets you capture SDK log lines, for example to show errors in your UI.
VERSION, SHASDK 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.

KeyTypeDescription
streamNamestringStream name to publish to (XXXXX-YYYYY). URL-encode any custom arguments yourself.
serverUrlstringWebRTC (WHIP) server. Default https://bintu-webrtc.nanocosmos.de/p/webrtc.
ingestUrlstringRTMP ingest the server forwards to. Default rtmp://bintu-stream.nanocosmos.de:1935/live.
previewVideoElIdstringID of the <video> element for startPreview()
inputCfgobjectInput and encoding settings, see below
reconnectboolean or objecttrue for defaults, or { minDelaySec, maxDelaySec, maxRetries }. See Automatic reconnection.
metricsobject{ accountId, accountKey } to send client metrics to nanoStream Analytics
authobject{ token }. Not active in the current version.

inputCfg​

KeyTypeDescription
mediaStreamMediaStreamYour own stream (camera, screen, canvas). If set, mediaStreamCfg is ignored.
mediaStreamCfgobjectSettings the SDK uses to create the stream itself, see below
broadcastCfgobjectEncoding limits, see below
muted{ audio?, video? }Start muted

inputCfg.mediaStreamCfg​

KeyTypeDescription
resolution[width, height]Requested resolution (an ideal value; the browser decides)
maxFrameratenumberMaximum capture frame rate
audioVideoOnly'audio' or 'video'Audio-only or video-only ingest
audioConstraintsobjectautoGainControl, echoCancellation, noiseSuppression, channelCount
audioDeviceIdstringdeviceId of the microphone to use
videoDeviceIdstringdeviceId of the camera to use

inputCfg.broadcastCfg​

KeyTypeDescription
maxVideoBitrateBpsnumberMaximum video bitrate in bits per second
maxAudioBitrateBpsnumberMaximum audio bitrate in bits per second
maxEncodingFrameratenumberMaximum encoded frame rate (not above maxFramerate)
transcodeAudioBitrateBpsnumberServer-side audio transcoding bitrate in bits per second

Methods​

All methods except the constructor need setup() first, unless noted.

MethodReturnsDescription
new Webcaster(config)WebcasterCreates 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?)voidAttaches 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? })voidMutes 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()UpstreamConnectionStatusConnection state. Can be called any time.
getMediaStreamSettings()MediaStreamSettingsSettings actually applied to the audio and video tracks
getConfiguredConstraints()MediaStreamConstraints or nullThe constraints the SDK built from your config

UpstreamConnectionStatus​

FieldType
connectionStateRTCPeerConnectionState or null
iceStateRTCIceConnectionState or null
gatheringStateRTCIceGatheringState or null
localDescriptionRTCSessionDescription or null
remoteDescriptionRTCSessionDescription or null

Callbacks​

Assign your own functions to these properties:

CallbackArgumentCalled when
onStateChangenoneThe Webcaster state changes. Read getUpstreamStatus() inside.
onConnectionStateChangeRTCPeerConnectionStateThe WebRTC connection state changes (connecting, connected, failed, …)
onReconnectionStateChangeReconnectionStateAutomatic reconnection changes state: idle, reconnecting, failed
onMetricsmetrics objectAt an interval during a broadcast, and immediately for errors
onErrorWebcasterErrorAn 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​

HelperDescription
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.

CodeNameMeaning
2001MStreamAlreadyExistsMediaStream already exists, for example setup() called twice
2002MStreamNotFoundNo MediaStream yet; setup() not called
2003MStreamNotCreatedCreating the MediaStream failed. See the message.
4000GeneralUnrecognised error
4001GeneralSetupNotCalledsetup() hasn't been called
4002GeneralBroadcastNotStartedstartBroadcast() hasn't been called
4003GeneralRecoveryFailedRecovery failed
4004GeneralLoggerSetupFailedLogger setup failed
5001BroadcastPCNotFoundNo peer connection yet, for example stopBroadcast() or dispose() called twice
5002BroadcastPCAlreadyExistsPeer connection exists, for example startBroadcast() called twice
5003BroadcastPCAddTransceiverFailedAdding a transceiver failed
5004BroadcastCreateOfferFailedCreating the offer failed, or the SDP was empty
5005BroadcastSetAnswerFailedSetting the answer failed
5006BroadcastApplyConstraintsFailedApplying constraints to a sender failed. Check broadcastCfg.
6001MDevicesMethodNotSupportedA MediaDevices method isn't available in this browser
6002MDevicesKindNotSupportedMedia device kind not supported
6003MDevicesPermissionQueryFailedPermission query for devices failed
7000ValidationErrorThe config failed validation. The message names the field.
8001MetricsParseUserAgentFailedParsing the user agent for metrics failed
8002MetricsInvalidTrackKindTrack kind for stats is not audio or video
8003MetricsInitStatsCollectFailedStarting stats collection failed
8004MetricsStopStatsCollectFailedStopping stats collection failed
10001ServerMalformedResponseServer response missing fields or with empty SDP
10002ServerCreateResourceFailedCreating the resource on the server failed
10003ServerRequestFailedServer error (HTTP 5xx). See the error's message and metadata.
11001ClientRequestFailedServer not reachable, or HTTP 4xx
11002ClientResourceAlreadyExistsA previous broadcast wasn't cleaned up
11003ClientResourceNotFoundResource doesn't exist, for example startBroadcast() not called yet
11004ClientRequestPendingA 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​

v5v6
new RtcUser()new WebcasterApiV6.Webcaster(config)
Event listeners: rtcUser.on('StartBroadcastSuccess', …), 'StartBroadcastError', …Methods return promises; use await with try/catch
signIn({ server, … }) before broadcastingNo 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 eventDeviceUtils.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​

VersionDateHighlights
6.2.42026-08-26Audio-only and video-only broadcasts only request the permission they need; device listing no longer depends on the other device kind.
6.2.02024-07-15More error codes, better session metrics; fixes for low resolutions in Chrome and for metrics sent after a failure.
6.1.02024-04-10Automatic reconnection. Fixes: dispose() could leave a dirty state; muted tracks are no longer re-enabled; isMuted() reports correctly.
6.0.22023-12-04First public v6 release

For all products, see Release notes.

Next steps​