watchRTC JS SDK
watchRTC enables application developers to collect, track and analyze telemetry and metrics of real users on any WebRTC application.
This is done by including our watchRTC SDK which connects to the testRTC backend and collects the relevant data.
Please check out our watchRTC knowledge base to learn more about the features and capabilities of this WebRTC monitoring service.
Installation
via NPM
npm install @testrtc/watchrtc-sdk
via Yarn
yarn add @testrtc/watchrtc-sdk
via CDN
<script src="https://unpkg.com/@testrtc/watchrtc-sdk/lib/index.js"></script>
Usage
Before any of your WebRTC javascript code, you need to include and initialize our SDK.
Inclusion and initialization
The watchRTC.init() needs to take place prior to including or loading any 3rd party SDKs that interact with WebRTC - failing to do so may hinder our ability to collect data.
Use the following initialization sequence:
javascript (ES6+)
const watchRTC = require("@testrtc/watchrtc-sdk");
watchRTC.init();
Typescript
import watchRTC from "@testrtc/watchrtc-sdk";
watchRTC.init();
javascript (ES5+)
with CDN
<!DOCTYPE html>
<html lang="en">
<head>
<title>watchRT SDK</title>
</head>
<body>
<script src="https://unpkg.com/@testrtc/watchrtc-sdk/lib/index.js"></script>
<script>
watchRTC.init();
</script>
</body>
</html>
Configuration
Before you start, be sure to also read our Getting started with watchRTC guide.
Configuring the SDK to connect to the watchRTC backend requires passing the following parameters to the SDK:
- rtcApiKey - watchRTC API key, as provided by testRTC
- rtcRoomId - an identifier to the session/room/conference. This will enable an analysis of all participants in the same room as a single logical unit. Read more about rooms and peers in watchRTC.
- rtcPeerId - an identifier of this peer/user in the session. This will make it easier to identify and troubleshoot users. It is recommended to use non-PII data here as much as possible (no emails or names for example)
- keys - (optional) key value object. Used to associate with this peer connection. These can later be searched for or filtered. Read more about keys in watchRTC.
- console - (optional) collect browser console log messages. Read more about collecting console logs in watchRTC.
- proxyUrl - (optional) secured web socket proxy server address, the proxy server should forward the connection to testRTC's watchRTC servers
Based on your application's logic, you can and should pass these configuration parameters at different stages. Read more about Setting up a proxy for watchRTC traffic.
- collectionInterval - (optional) the number of seconds in which watchRTC will collect stats. Used until the connection to watchRTC server won't be opened. Read more about collection interval in watchRTC
- In the call to the
watchRTC.init()
- In the call to
watchRTC.setConfig()
- Upon the creation of an
RTCPeerConnection()
via watchRTC.init()
Passing configuration parameters in the init() is the direct/easy way to provide this information.
This is useful if you are planning to use a known/specific roomId for this session.
The disadvantage of this approach is that it is rigid, and doesn't allow much flexibility.
You can call the init()
function multiple times, but it will be initialized only on the first call.
watchRTC.init({
rtcApiKey: "watchRTC API key",
rtcRoomId: "identifier for the session",
rtcPeerId: "identifier for the current peer",
keys: { key1: "value1", key2: "value2" },
console: { level: "error", override: true },
proxyUrl: "wss://{your-proxy}",
collectionInterval: 8,
});
You can call init()
multiple times, but it will be initialized only at the first time. Following calls will be ignored.
via watchRTC.setConfig()
You can use watchRTC.setConfig()
function to set watchRTC configuration after calling watchRTC.init()
and before the creation of RTCPeerConnection objects.
This approach is useful if you don't have the information needed in your watchRTC.init()
call or when you don't have direct/easy access to the RTCPeerConnection objects (for example, when using a third party CPaaS SDK).
If needed, you can pass the rtcApiKey in the watchRTC.init()
call while passing the rtcRomId, rtcPeerId and keys in the watchRTC.setConfig()
call.
You can call this function multiple times, usually whenever a new session/room needs to be created or entered.
watchRTC.setConfig({
rtcApiKey: "watchRTC API key",
rtcRoomId: "identifier for the session",
rtcPeerId: "identifier for the current peer",
keys: { key1: "value1", key2: "value2" },
console: { level: "error", override: true },
});
via RTCPeerConnection()
If you have direct access to the RTCPeerConnection object creation, then you can add the necessary configuration parameters there. This gives you the highest level of control over what is done.
var pc = new RTCPeerConnection({
...,
watchrtc:{
rtcApiKey: "watchRTC API key",
rtcRoomId: "identifier for the session",
rtcPeerId: "identifier for the current peer",
keys: { key1: "value1", key2: "value2" },
console: { level: "error", override: true }
}
});
Open/Close connection to server
By default, watchRTC SDK will automatically establish a connection with the watchRTC server and close it after an idle period. At times, it might make sense for your application to manually open and close that connection explicitly. This is done by calling watchRTC.connect()
and watchRTC.disconnect()
. Read more about manually connecting/disconnecting to watchRTC servers.
watchRTC.connect();
watchRTC.disconnect();
Adding keys
You can also add keys to a room after joining the room. This can be done by calling watchRTC.addKeys()
function.
Returns a Promise
which resolves with an empty object in success case, or with an error
property if something went wrong.
- keys - These can later be searched for or filtered. Read more about keys in watchRTC.
watchRTC.addKeys({ key1: "value1", key2: "value2" });
Enabling and disabling data collection
When needed, you can temporarily disable data collection. This is important for example if you want to conduct a pre-call test but you aren't interested in collecting that data.
For that, you can use watchRTC.enableDataCollection()
and watchRTC.disableDataCollection()
to control what data you want to send.
Adding user ratings
You can collect the user's feedback as well. This can be done by calling watchRTC.setUserRating()
.
Returns a Promise
which resolves with an empty object in success case, or with an error
property if something went wrong.
- rating - A number from 1 to 5. You can use it for a 5-stars rating system, or you can use 1 and 5 values only for a like/dislike type of rating system
- comment - (optional) Simple string value, collecting user's "verbal" feedback
watchRTC.setUserRating(5, "the best video quality I ever experienced!");
Adding events
You can add your own events to the graphs and event logs. This enables you to monitor specific activity that you are interested in that is outside the generic scope of how WebRTC operates but part of your application logic. This is done by calling watchRTC.addEvent()
.
Returns a Promise
which resolves with an empty object in success case, or with an error
property if something went wrong.
Read more about adding custom events in watchRTC.
- name - The event name. This will be displayed when the event occurred
- type - One of the following event types
- "log" - the event will appear only on the event log in the Advanced WebRTC Analytics for the peer
- "local" - the event will be in the event log as well as placed on the peer level charts
- "global" - the event will be in the event log, peer level charts and on the room level charts
- parameters - (optional) JSON object to attach to the event. This will appear in the event log
watchRTC.addEvent({ name: "my event", type: "global", parameters: { param1: "value1" } });
Starting version 1.38, events can be associated to a RTCPeerConnection
. Here is an example:
const audioPc = new RTCPeerConnection();
watchRTC.addEvent({
name: "muted",
type: "local",
parameters: { value: true },
pc: audioPc,
});
Mapping streams (deprecated in favor of Mapping tracks)
By default, watchRTC will assign the SSRC information as the name for incoming channels. You can change these to human-readable format indicating the source of the channels by mapping their streams. This is done by calling watchRTC.mapStream(streamIdentifier)
. Read more about mapping streams in watchRTC.
- id - the StreamIdentifier to map from in the PeerConnection object
- name - the human-readable name to assign and display for it
watchRTC.mapStream("lyk0zS1eyvZfJRLis3OIwBx3UvH3:oxrhEtb3sV7VutbQ:video", "User A");
Mapping tracks
By default, watchRTC will assign the SSRC information as the name for incoming channels. You can change these to human-readable format indicating the source of the channels by mapping their streams. This is done by calling watchRTC.mapTrack(trackIdentifier)
. Read more about mapping streams in watchRTC.
- id - the TrackIdentifier to map from in the PeerConnection object
- name - the human-readable name to assign and display for it
watchRTC.mapTrack("c085d50a-bb28-4d9f-97b1-86bfc646e5b0", "User A");
Note: The trackIdentifier
corresponds to the remote RTCMediaStreamTrack's Id attribute.
Persistent connections and nailup calls
In call center scenarios, there's a feature called persistent connection or nailup call. With it, a WebRTC peer connection is created and maintained, while actual real calls take place on top of that single connection, keeping it open in-between these calls. This is used to reduce call setup times and to reduce the amount of needed signaling messages. You can mark the begining and end of such application specific calls on a persistent connection using watchRTC.persistentStart(rtcRoomId, rtcPeerId)
and watchRTC.persistentEnd()
. Read more about persistent connections and watchRTC.
Note: Make sure to pass new rtcRoomId for next call in order to separate sessions.
Collect WebRTC statistics (BETA)
Be careful, this API is in beta. API and content could change in the next version.
Once a call is established, WatchRTC exposes WebRTC statistics collected from the existing RTCPeerConnections. Accessing to these statistics can be done by adding a listener from the application.
const statsListener = (stats) => {
};
watchRTC.addStatsListener(statsListener);
Each time new statistic are available, the listener will be called with a JSON object containing the statistics.
The JSON object contains 2 main properties:
- connections: Which lists the connections (based on the RTCPeerConnection used) and the properties associated to each connection,
- streams: Which lists all the streams involved in the call
For each connection in connections, the following properties are available:
- connection: String value. Can be one of
direct
or relay
, - transport: String value. Can be one of
udp
, tcp
or tls
, - address: String value using format 'address:port'. This is the remote IP address and port,
For each stream in streams, the following properties are available:
- peerID: String value. This is the ID of the associated connection,
- kind: String value. Can be one of
audio
or video
, - direction: String value. Can be one of
inbound
or outbound
, - mappedName: String value. The name given when calling
mapTrack
and associated with this stream. null
by default, - codec: The name of the codec used,
- jitter: Number in seconds. Average during the last interval. Null if not available,
- roundTripTime: Number in seconds. Average during the last interval. Null if not available,
- bytesReceived: (Inbound streams only). Number of bytes received during the last interval. Null if not available,
- bytesSent: (Outbound streams only). Number of bytes sent during the last interval. Null if not available,
- packetsReceived: (Inbound streams only). Number of packets received during the last interval. Null if not available,
- packetsSent: (Outbound streams only). Number of packets sent during the last interval. Null if not available.
- packetsLost: Number of packets sent or received that has been lost during the last interval. Null if not available,
- packetsLoss: Percent of packets sent of received that has been lost during the last interval. Null if not available,
- bitrate: Number of bits sent or received per second. Average during the last interval. Null if not available,
- frameWidth: (Video streams only). Number of pixels for the width of the video. Null if not available,
- frameHeight: (Video streams only). Number of pixels for the height of the video. Null if not available,
- framerate: (Video streams only). Number of frame per second. Null if not available,
Note: To stop receiving the statistics, pass null
to the addStatsListener
function. The existing listener will be unsubscribed and removed.
Listen to the SDK's connectivity state
Once the watchRTC SDK is initialized, it will report its state changes. Listening to the state can be done by adding a listener from your application.
const stateListener = (state) => {
};
watchRTC.addStateListener(stateListener);
Each time the state changes, the listener will be called with a JSON object containing new state.
The JSON object contains 1 property:
- connectionStatus: String value. Can be one of
connected
or disconnected
,
Note: To stop listening, pass null
to the addStateListener()
function. The existing listener will be unsubscribed and removed.
Samples
Additional samples on how to integrate the watchRTC SDK can be found on our official GitHub repository:
https://github.com/testRTC/sample-Twilio-video-app-React-TypeScript-watchRTC
Changelog
1.38.0.beta-5 (Oct 18, 2023)
- fix "flush any data that is older than the last 10 minutes" logic, which would cause missing events
1.38.0.beta-4 (Oct 16, 2023)
- add more info about "close" event log in debug mode
- "nailUpCallEnd" log message does not include timestamp, which can cause incorrect time calculations
1.38.0.beta-3 (Oct 09, 2023)
- add
logLevel
configuration property to give more control over logs on SDK initialization - deprecated
debug
configuration property in favor of logLevel
- flush any data that is older than the last 10 minutes and not send it to the server before first connection with server
1.38.0.beta-2 (Sep 28, 2023)
- removed
track.mute
and track.unmute
events to minimize messages in logs in the case of large rooms or for peers with large number of channels. - better handling nail-up calls by calculating a report used as reference each time a call to
persistentStart()
is done. This avoids the initial spike in graphs.
1.38.0.beta-1 (Aug 28, 2023)
- added
pc
property in addEvent
to associate the event to an existing RTCPeerConnection
- stop logging credentials of iceServer configuration
1.37.0.beta-3 (Jul 19, 2023)
Bug fixes
- added
codec
in statsListener - fixed wrong message displayed in the console when configuration parameters have been set via
RTCPeerConnection
- better handling events on tracks to avoid removing application listeners
1.37.0.beta-1 (May 12, 2023)
Bug fixes
- better handling collection interval mismatch case
1.36.3 (Apr 5, 2023)
- removed
getStats
logs in debug mode to reduce resources usage - added
logGetStats
configuration property to enable getStats
logs if needed
1.36.2 (Feb 21, 2023)
1.36.1 (Feb 20,2023)
Add more debug logs
- added debug logs for
persistentStart
and persistentEnd
methods
1.36.0 (Feb 16,2023)
Handle NailUp calls behaviour
- Added internal global sessionId
- Use
watchRTC.persistentStart(rtcRoomId, rtcPeerId)
and watchRTC.persistentEnd()
to start/stop nail up call. Make sure to pass new rtcRoomId for next call in order to separate sessions.
Deprecation methods
watchRTC.mapStream() method is deprecated and should be replaced by watchRTC.mapTrack()
New features
watchRTC.mapTrack()
was added- Property
mappedName
added to the statsListener
which contains the name associated to the stream.
1.35.3 (Dec 6, 2022)
New features
watchRTC.addStateListener()
was added
1.35.2 (Nov 8, 2022)
- Fixed media soup compatibility issues
- Fixed console logs not beeing collected in case of "early"
setConfig
1.35.0 (Sep 26, 2022)
- Fixed bugs around "override console" feature
- Improved SDK stability
1.35.0-beta.2 (Sep 12, 2022)
Bug fixes
- Better handle "Converting circular structure to JSON" error when override console
1.35.0-beta.1 (Aug 25, 2022)
New features
- Console warning if RTCPeerConnection object has been overriden before sdk initialization
1.34.1-beta.14 (July 22, 2022)
New features
- Add support for multiple server versions
1.34.1-beta.12 (July 22, 2022)
Bug fixes
- Add new debug log for "getStats" method
1.34.1-beta.10 (July 12, 2022)
Bug fixes
- Handle "Converting circular structure to JSON" error when override console
1.34.1-beta.7 (July 8, 2022)
Bug fixes
- HTTP trace did not work if websocket connection was not established in the first place
1.34.1-beta.5 (July 6, 2022)
Bug fixes
- Console override now happens only if console logs are requested to be collected
- When getstats timestamp property was provided as a string, data compression failed to work
- Sometimes RTCRemoteInboundRTPAudio and RTCRemoteInboundRTPVideo reports were missed, resulting in a gap at the beginning of our chart data
addEvent
now works more accurately for events captured before the websocket connection was established to the watchRTC server
1.33.6 (June 8, 2022)
New features
- You can now collect console logs using the SDK. Read more about Collecting console logs in watchRTC
- The SDK now tries to reconnect if it loses its connection to the watchRTC server
- We now queue custom events if the SDK isn't connected to the server. These get sent to the server once a connection is available
- You can now open/close the connection to server manually. Read more about manually connecting/disconnecting to watchRTC servers
- You can now
await
on the following SDK methods: addKeys()
, setUserRating()
, addEvent()
. These methods now return a Promise
which resolves with an empty object on success case, or with an error
property if something went wrong
1.30.8 (February 15, 2022)
Bug fixes
- We now capture getUserMedia failures as well. These will be collected and reported if a peer connection object is created by the application
1.30.7 (February 14, 2022)
Bug fixes
- Sometimes watchRTC froze when initiating a session. That has been fixed
1.30.6 (November 19, 2021)
New features
- Added support for custom keys with multiple values
watchRTC.addEvent()
now also supports parameters
1.30.5 (November 19, 2021)
New features
watchRTC.mapStream()
was added. Read more about mapping streams in watchRTCwatchRTC.addEvent()
was added. Read more about events in watchRTC- icecandidateerror() events are now collected by the SDK
- RTCRtpSender.setParameters() calls are now collected by the SDK
- Added support for parameterless setLocalDescription() calls
1.30.4 (October 12, 2021)
- Fixed data collect when using Firefox
- Fixed a CSP warning by making the watchRTC SDK self-suficient without any external dependencies
1.30.3 (October 5, 2021)
1.30.2 (October 3, 2021)
Bug fixes
- The SDK now doesn't collect WebRTC API calls into the event log twice
1.30.0 (September 26, 2021)
New features
watchRTC.addTags()
was deprecated. We no longer support tags. These have been replaced with a key/value systemwatchRTC.addKeys()
was added. Read more about keys in watchRTC
1.29.2 (July 22, 2021)
New features
watchRTC.addTags()
was addedwatchRTC.setUserRating()
was added