### Webcaster Setup and Start Broadcast
Source: https://docs.nanocosmos.net/docs/webrtc/nanostream_webrtc_getting_started
Imports Webcaster and Config, creates a configuration with a stream name, instantiates the client, and then calls setup, startPreview, and startBroadcast to begin streaming.
```typescript
import { Config as WebcasterConfig, Webcaster } from '../../dist/nanostream.webcaster';
const config: WebcasterConfig = {
streamName: 'my-nanostream-name'
};
const client = new Webcaster(config);
client.setup().then(fullCfg => {
console.log(fullCfg);
client.startPreview('myPreviewElId');
client.startBroadcast();
});
```
--------------------------------
### Config example with stream group
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_feature_stream_group_configuration
JavaScript configuration example for the player, passing group.id, security.jwtoken, and startQuality. Use this in your player setup.
```javascript
var config = {
"source": {
"group": {
"id": "xxxxxxxx-zzzz-yyy-aaaa-aaabbbcccddd", // your stream group id
"security": { // required for secure group playback
"jwtoken": "xxx" // your security token if applicable
},
"startQuality": "medium" // optional
},
...
},
...
};
```
--------------------------------
### onStartBuffering event handler example
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Assigns an onStartBuffering handler to config.events and calls player.setup(). The handler logs 'Buffering'. The setup call logs the config on success or the error on failure.
```javascript
// player instance of NanoPlayer
var onStartBuffering = function (event) {
console.log('Buffering');
};
config.events.onStartBuffering = onStartBuffering;
player.setup(config).then(function (config) {
console.log('setup ok with config: ' + JSON.stringify(config));
}, function (error) {
console.log(error);
});
```
--------------------------------
### Replay/reconnect example: HTML setup with player config
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api_errors
HTML page with a player div, a checkbox to enable replay, and a script tag loading the nanoPlayer. The configuration object defines a bintu source with an RTMP stream entry; the stream name placeholder must be replaced.
```html
```
```javascript
```
```javascript
```
--------------------------------
### Secure Entries Configuration - Config Example
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_security_jwt
JavaScript config example using entries configuration with secure H5Live server URLs and a jwtoken. Use this when configuring the player with an entries source.
```javascript
var config = {
"source": {
"entries": [
{
"h5live": {
"rtmp": {
"url": "rtmp://bintu-splay.nanocosmos.de/splay",
"streamname": 'XXXXX-YYYYY' // your streamname
},
"server": {
"websocket": "wss://bintu-h5live-secure.nanocosmos.de/h5live/authstream",
"hls": "https://bintu-h5live-secure.nanocosmos.de/h5live/authhttp/playlist.m3u8"
},
"security": {
"jwtoken": "xxx" // your JSON Web Token
}
}
}
]
...
},
...
};
```
--------------------------------
### nanoPlayer configuration example
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Example configuration object for the nanoPlayer, showing source, playback, events, style, tweaks, and metrics settings. The source includes RTMP and server URLs, with a comment noting webtransport is important for MOQ playback. Playback is optional, and metrics require an account.
```javascript
"rtmp": {
"url": "rtmp://bintu-play.nanocosmos.de/play",
"streamname": "XXXXX-YYYY3"
},
"server": {
"websocket": "wss://bintu-h5live.nanocosmos.de:443/h5live/stream.mp4",
"hls": "https://bintu-h5live.nanocosmos.de:443/h5live/http/playlist.m3u8",
"progressive": "https://bintu-h5live.nanocosmos.de:443/h5live/http/stream.mp4",
"webtransport": "https://bintu-h5live.nanocosmos.de:443/h5live/stream/stream.mp4" // important for MOQ playback,
},
"token": "",
"security": {}
},
"bintu": {}
}
],
"options": {
"adaption": {
"rule": "deviationOfMean2",
"downStep": 2
},
"switch": {
'method': 'server',
'pauseOnError': false,
'forcePlay': true,
'fastStart': false,
'timeout': 20
}
},
"startIndex": 2 // lowest
},
// playback is completely optional
"playback": {
"autoplay": true,
"automute": true,
"muted": false,
"faststart": true,
"latencyControlMode": 'balancedadaptive',
"metadata": true,
"reconnect": {
"minDelay": 2.5,
"maxDelay": 12.5,
"delaySteps": 6,
"maxRetries": 20
},
"videoId": ['myVideoTagId', 'myVideoTagId']
},
"events": {
"onWarning": function (e) {
console.log(e);
}
},
"style": {
"width": '1280px',
"height": '720px'
},
// optional buffer tweaks, use with care, usually not required
"tweaks": {
"buffer": {
"min": 0.2,
"start": 0.5,
"max": 8.0,
"target": 1.2,
"limit": 1.7
}
},
// metrics/analytics (requires account)
"metrics": {
"accountId": 'myId',
"accountKey": 'sdfhe457zsjhnrtzd8',
"userId": 'myUserId',
"eventId": 'myEventId',
"statsInterval": 10,
"customField1": 'custom',
"customField2": 42,
"customField3": true
}
};
```
--------------------------------
### Load NanoPlayer with new video element into playerDiv
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Shows the basic setup of NanoPlayer with a new video element created by the player. Includes the HTML div, script tag loading nanoplayer.5.min.js, and the JavaScript configuration with RTMP stream and server URLs. The setup() promise logs success or error.
```html
```
--------------------------------
### HTML for device dropdown example
Source: https://docs.nanocosmos.net/docs/webrtc/nanostream_webrtc_device_selection
HTML markup for the device dropdown example, containing a heading and a div element with id 'devices' where the dropdowns will be appended.
```html
MediaDevices:
```
--------------------------------
### Ping example output for google.com
Source: https://docs.nanocosmos.net/docs/cloud/network-diagnostics
Example output from ping showing successful replies with RTT times.
```bash
PING google.com (216.58.217.110): 56 data bytes
64 bytes from 216.58.217.110: icmp_seq=0 ttl=54 time=14.8 ms
64 bytes from 216.58.217.110: icmp_seq=1 ttl=54 time=16.6 ms
64 bytes from 216.58.217.110: icmp_seq=2 ttl=54 time=16.5 ms
```
--------------------------------
### Full Request Path Example
Source: https://docs.nanocosmos.net/docs/webrtc/nanostream_webrtc_whip_ingest
Example of a full WHIP request path with stream_name as a string and stream_url pointing to the RTMP endpoint.
```text
https://bintu-webrtc.nanocosmos.de/p/webrtc?stream_name=&stream_url=rtmp://bintu-stream.nanocosmos.de/live
```
--------------------------------
### Startup error event example: code 2003
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api_errors
Example event object for a 2003 startup error that occurred after the loading timeout fired. No media data was received but the connection was healthy; `data.playback` shows zero values and `data.state` only contains `connected` and `error` timestamps.
```json
{
"name": "Error",
"data": {
"code": 2003,
"message": "Not enough media data received.",
"playback": {
"bufferDelayCurrent": 0,
"bitrateCurrent": 0,
"framerateCurrent": 0
},
"state": {
"connected": 392,
"error": 10004
}
},
"player": "playerDiv",
"id": "69537640939",
"version": "4.28.0",
"state": 4
}
```
--------------------------------
### nanoPlayer.play() example
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Plays the player.
```javascript
// player instance of NanoPlayer
player.play();
```
--------------------------------
### nanoPlayer.setup(config) example
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Initializes the player with a config object. The promise resolves with the config on success or rejects with an error on failure.
```javascript
// player instance of NanoPlayer
player.setup(config).then(function (config) {
console.log('setup ok with config: ' + JSON.stringify(config));
}, function (error) {
console.log(error);
});
```
--------------------------------
### Set up Webcaster instances
Source: https://docs.nanocosmos.net/docs/webrtc/nanostream_webrtc_multiple_webcasts
Calls setup() on both instances to prepare them for use. This step creates a media stream if not passed and configures internal settings. The calls can be run in parallel.
```javascript
await camWebcaster.setup(),
await screenWebcaster.setup()
```
--------------------------------
### Handle onStats event in NanoPlayer setup
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Example of assigning an onStats handler to config.events.onStats before calling player.setup. Logs the stats object as JSON and logs the setup result or error.
```javascript
// player instance of NanoPlayer
var onStats = function (event) {
console.log('Stats: ' + JSON.stringify(event.data.stats));
};
config.events.onStats = onStats;
player.setup(config).then(function (config) {
console.log('setup ok with config: ' + JSON.stringify(config));
}, function (error) {
console.log(error);
});
```
--------------------------------
### nanoPlayer.setup(config) ⇒ Promise.<(config|error)>
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Initializes the player with a given config object. Returns a promise that resolves with the config or rejects with an error.
```APIDOC
## nanoPlayer.setup(config) ⇒ `Promise.<(config|error)>`
### Description
Initializes the player with a given config object.
### Method
setup
### Parameters
- **config** (`config`) - Required - The config object for the player including sources, events, styles.
### Request Example
```js
// player instance of NanoPlayer
player.setup(config).then(function (config) {
console.log('setup ok with config: ' + JSON.stringify(config));
}, function (error) {
console.log(error);
});
```
### Response
#### Success Response
- **config** (`config`) - The resolved config object.
#### Error Response
- **error** (`error`) - The error object if setup fails.
```
--------------------------------
### nanoPlayer.destroy() example
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Cleans up the player and removes all nested elements from the container div, then re-initializes it with setup.
```javascript
// player instance of NanoPlayer
player.destroy();
player.setup(config);
```
--------------------------------
### React.js: Initialize setup with React Hooks
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_getting_started
Use useEffect to call setupNanoplayer when the component mounts.
```javascript
useEffect(() => {
setupNanoplayer(config);
}, [])
```
--------------------------------
### Secure H5Live Player - Web Page Example
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_security_jwt
Complete HTML page example for embedding the H5Live player with a secure stream group. Includes the NanoPlayer script, config with jwtoken, and setup with success/error handling.
```html
```
--------------------------------
### Handle StartBroadcastError event
Source: https://docs.nanocosmos.net/docs/faq/faq_WebRTC_devices
Listen to the StartBroadcastError event to handle errors when starting a broadcast. The example logs the error text to the console.
```javascript
user.on("StartBroadcastError", function(evt){
// handle error
console.log((event.data.text);
});
```
--------------------------------
### onStreamInfo event handler for NanoPlayer setup
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Registers the onStreamInfo event handler in config.events before calling player.setup(config). The handler logs the stream info object when the event fires right before playback starts. The setup promise logs success or error.
```javascript
// player instance of NanoPlayer
var onStreamInfo = function (event) {
console.log('StreamInfo: ' + JSON.stringify(event.data.streamInfo));
};
config.events.onStreamInfo = onStreamInfo;
player.setup(config).then(function (config) {
console.log('setup ok with config: ' + JSON.stringify(config));
}, function (error) {
console.log(error);
});
```
--------------------------------
### Change video background color in promise resolve function
Source: https://docs.nanocosmos.net/docs/faq/faq_h5live_player_adjust_style
Workaround for older H5Live Player versions: select the video element in the resolve function of the setup promise and change its background color. This example shows a full player setup with a bintu source and the style modification.
```javascript
var player;
var config = {
"source": {
"bintu": {
"apiurl": "https://bintu.nanocosmos.de",
"streamid": "236af21e-fbf3-4ba3-889c-343ef3f0e7ca"
}
},
"playback": {
"autoplay": true,
"automute": true,
"muted": false
},
"style": {
"controls": true,
"width": "auto",
"height": "auto",
}
};
document.addEventListener('DOMContentLoaded', function () {
player = new NanoPlayer("playerDiv");
player.setup(config).then(function (config) {
console.log("setup success");
console.log("config: " + JSON.stringify(config, undefined, 4));
var video = document.querySelector('#playerDiv video');
video.style.backgroundColor = '#123456';
}, function (error) {
alert(error.message);
});
});
```
--------------------------------
### Config example using service defaults and custom server urls
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_feature_source_defaults
Configuration combining source defaults with custom server URLs. The defaults service fills gaps but does not overwrite explicitly defined values.
```javascript
var config = {
"source": {
"defaults": {
"service": "bintu"
},
"entries": [
{
"h5live": {
// your rtmp stream
"rtmp": {
"streamname": "XXXXX-YYYYY"
},
"server": {
"websocket": "wss://[your_path]",
"hls": "https://[your_path]",
"progressive": "https:/[your_path]",
"webtransport": "https:/[your_path]" // important for MOQ playback
}
}
}
]
}
};
```
--------------------------------
### Config example with service defaults
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_feature_source_defaults
Configuration using source defaults: only the streamname is required in the entry; h5live.server and h5live.rtmp.url are omitted and defaults are applied.
```javascript
var config = {
"source": {
"defaults": {
"service": "bintu"
},
"entries": [
{
"h5live": {
// your rtmp streamname
"rtmp": {
"streamname": "XXXXX-YYYYY"
}
}
}
]
}
};
```
--------------------------------
### Video-Only Streaming: Set audioVideoOnly to 'video'
Source: https://docs.nanocosmos.net/docs/webrtc/nanostream_webrtc_audio_video_only
Configure the Webcaster to stream only video by setting mediaStreamCfg.audioVideoOnly to 'video'. The example shows the full constructor call and the subsequent setup and startBroadcast calls.
```javascript
const webcaster = new window.WebcasterApiV6.Webcaster({
inputCfg: {
mediaStreamCfg: {
audioVideoOnly: 'video'
}
},
ingestUrl: 'rtmp://bintu-stream.nanocosmos.de:1935/live',
serverUrl: 'https://bintu-webrtc.nanocosmos.de/p/webrtc',
streamName: ''
});
await webcaster.setup()
await webcaster.startBroadcast()
```
--------------------------------
### Audio-Only Streaming: Set audioVideoOnly to 'audio'
Source: https://docs.nanocosmos.net/docs/webrtc/nanostream_webrtc_audio_video_only
Configure the Webcaster to stream only audio by setting mediaStreamCfg.audioVideoOnly to 'audio'. The example shows the full constructor call and the subsequent setup and startBroadcast calls.
```javascript
const webcaster = new window.WebcasterApiV6.Webcaster({
inputCfg: {
mediaStreamCfg: {
audioVideoOnly: 'audio'
}
},
ingestUrl: 'rtmp://bintu-stream.nanocosmos.de:1935/live',
serverUrl: 'https://bintu-webrtc.nanocosmos.de/p/webrtc',
streamName: ''
});
await webcaster.setup()
await webcaster.startBroadcast()
```
--------------------------------
### Handle H5Live setup error for unsupported browser
Source: https://docs.nanocosmos.net/docs/faq/faq_h5live_player_general
Shows a nanoPlayer.setup() call with a success and error callback. The error callback alerts the browser support error message when the browser lacks required HTML5 features. Use this to catch unsupported browsers and inform the user.
```javascript
player.setup(config).then(function (config) {
console.log("setup success");
}, function (error) {
alert(error.message);
});
```
--------------------------------
### Get latest live stream with cURL
Source: https://docs.nanocosmos.net/docs/cloud/bintu_api
Retrieves the newest stream(s) in your organization (default is 50). Uses the X-BINTU-APIKEY header for authentication and the QUANTITY parameter to limit results. This example requests one stream.
```bash
curl -X GET "https://bintu.nanocosmos.de/stream?quantity=1" \
-H 'content-type: application/json' \
-H 'x-bintu-apikey: YOUR_BINTU_API_KEY'
```
--------------------------------
### MTR report to example.com
Source: https://docs.nanocosmos.net/docs/cloud/network-diagnostics-mtr
Example command to test the route and connection quality to example.com.
```bash
mtr -rw example.com
```
--------------------------------
### Multi stream configuration with ABR and playback security
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_feature_stream_switching
This example is a continuation of the multi stream configuration with ABR, adding playback security settings. The source text is truncated, so only the beginning of the configuration is shown.
```javascript
var config = {
"source" : {
"entries": [ // array of 'entry' objects
{
"index": 0,
"label": "high",
"tag": "this is a high quality stream",
"info": {
```
--------------------------------
### React.js: Initialize setup with componentDidMount
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_getting_started
Use componentDidMount to call setupNanoplayer with the config from state.
```javascript
componentDidMount() {
setupNanoplayer(this.state.config);
}
```
--------------------------------
### Get latest live stream with JavaScript
Source: https://docs.nanocosmos.net/docs/cloud/bintu_api
Retrieves the newest stream(s) in your organization (default is 50). Uses the x-bintu-apikey header for authentication and the quantity query parameter to limit results. This example requests one stream.
```javascript
fetch("https://bintu.nanocosmos.de/stream?quantity=1", {
method: "GET",
headers: { "x-bintu-apikey": BINTU_API_KEY }
}).then(response => response.json());
```
--------------------------------
### Handle onSwitchStreamInit event
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Attach a handler to the onSwitchStreamInit event to log the rule, type, entry, options, tag, and count. This event is the start of a stream switch request, triggered by ABR or switchStream. The example also sets up the player and logs the configuration or error.
```javascript
// player instance of NanoPlayer
var onSwitchStreamInit = function (event) {
console.log('switch stream init by rule ' + event.data.rule + ' from type ' + event.data.type + 'with entry: ' + JSON.stringify(event.data.entry) + ' and options: ' + JSON.stringify(event.data.options));
console.log('switch stream tag: ' + event.data.tag);
console.log('switch stream count: ' + event.data.count);
};
config.events.onSwitchStreamInit = onSwitchStreamInit;
player.setup(config).then(function (config) {
console.log('setup ok with config: ' + JSON.stringify(config));
}, function (error) {
console.log(error);
});
```
--------------------------------
### JavaScript to populate device dropdowns
Source: https://docs.nanocosmos.net/docs/webrtc/nanostream_webrtc_device_selection
JavaScript example that uses DeviceUtils.getAvailableMediaDevices and DeviceUtils.filterDevices to create separate dropdowns for video and audio input devices, appending them to the #devices div. Includes a helper function to create a select element with options for each device.
```javascript
DeviceUtils.getAvailableMediaDevices().then(devices => {
const videoDevices = DeviceUtils.filterDevices(devices, ['videoinput']);
const audioDevices = DeviceUtils.filterDevices(devices, ['audioinput']);
console.debug('Available devices:', devices);
const devicesDiv = document.querySelector('#devices')
const videoDevicesSelect = createDevicesDropdown(videoDevices);
const audioDevicesSelect = createDevicesDropdown(audioDevices);
const videoDevicesLabel = document.createElement('label');
videoDevicesLabel.innerText = 'video devices: ';
const audioDevicesLabel = document.createElement('label');
audioDevicesLabel.innerText = 'audio devices: ';
devicesDiv.appendChild(videoDevicesLabel);
devicesDiv.appendChild(videoDevicesSelect);
devicesDiv.appendChild(document.createElement('br'));
devicesDiv.appendChild(audioDevicesLabel);
devicesDiv.appendChild(audioDevicesSelect);
});
function createDevicesDropdown(devices) {
// Create a select element
const selectElement = document.createElement('select');
devices.forEach(device => {
const optionElement = document.createElement('option');
optionElement.value = device.deviceId;
optionElement.textContent = `${device.label || 'Unknown Device'} - id: ${device.deviceId}` ;
selectElement.appendChild(optionElement);
});
return selectElement;
}
```
--------------------------------
### Handle onSwitchStreamSuccess event
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Attach a handler to the 'onSwitchStreamSuccess' event to log the switch rule, type, entry, tag, and count when a stream switch succeeds. The event fires after the source is updated and follows the 'onSwitchStreamInit' start event. The example assumes a NanoPlayer instance and a config object with an events property.
```javascript
// player instance of NanoPlayer
var onSwitchStreamSuccess = function (event) {
console.log('switch stream success by rule ' + event.data.rule + ' from type ' + event.data.type + 'with entry: ' + JSON.stringify(event.data.entry) + ' with tag: ' + event.data.tag + ' and count: ' + event.data.count);
};
config.events.onSwitchStreamSuccess = onSwitchStreamSuccess;
player.setup(config).then(function (config) {
console.log('setup ok with config: ' + JSON.stringify(config));
}, function (error) {
console.log(error);
});
```
--------------------------------
### Handle onSwitchStreamFail event
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_api
Attach a handler to the 'onSwitchStreamFail' event to log the rule, type, entry, error code, message, tag, and count when a stream switch fails. The event fires when an error occurs during the update and follows the 'onSwitchStreamInit' start event. The example assumes a NanoPlayer instance and a config object with an events property.
```javascript
// player instance of NanoPlayer
var onSwitchStreamFail = function (event) {
console.log('switch stream fail by rule ' + event.data.rule + ' from type ' + event.data.type + 'with entry: ' + JSON.stringify(event.data.entry) + ' with error code: ' + event.data.code + ' and error message: ' + event.data.message);
console.log('switch stream tag: ' + event.data.tag);
console.log('switch stream count: ' + event.data.count);
};
config.events.onSwitchStreamFail = onSwitchStreamFail;
player.setup(config).then(function (config) {
console.log('setup ok with config: ' + JSON.stringify(config));
}, function (error) {
console.log(error);
});
```
--------------------------------
### Install MTR on macOS with MacPorts
Source: https://docs.nanocosmos.net/docs/cloud/network-diagnostics-mtr
Command to install MTR using MacPorts on macOS.
```bash
port install mtr
```
--------------------------------
### Enable fast playback start in configuration
Source: https://docs.nanocosmos.net/docs/nanoplayer/nanoplayer_feature_fast_start
Set the faststart property to true within the playback configuration object to enable the feature.
```javascript
'config': {
...
'playback': {
'faststart': true,
...
},
...
}
```