webrtc-anonymous-js-sdk

7.10.0

create

The SDK creation factory. Create an instance of the SDK by calling this factory with the desired configurations. The SDK instance will be referred as 'api' throughout the rest of the documentation content.

create(config: config): api
Parameters
Name Description
config config The configuration object.
Returns
api: The SDK instance.
Example
// Instantiate the SDK.
import { create } from '@rbbn/webrtc-js-sdk'
const client = create({
    authentication: { ... },
    logs: { ... },
    ...
});
// Use the SDK's API.
client.on( ... );

config

The configuration object. This object defines what different configuration values you can use when instantiating the SDK using the create function.

config
Configurations By Feature
config.logs
config.connectivity
config.notifications
config.request
config.authentication
config.subscription
config.call

addMedia

Add new media tracks to an ongoing call. Will get new media tracks from the specific sources to add to the call.

The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:newTrack event both for the local and remote users to indicate a track has been added to the Call.

addMedia(callId: string, media: Object, options: Object?)
Parameters
Name Description
callId string The ID of the call to add media to.
media Object (default {}) The media options to add to the call.
media.audio boolean (default false) Whether to add audio to the call.
media.video boolean (default false) Whether to add video to the call.
media.screen boolean (default false) Whether to add the screenshare to the call. (Note: Screensharing is not supported on iOS Safari.)
media.medias Array<media.DetachedMedia>? List of detached medias containing tracks to be attached to this call.
media.audioOptions call.AudioOptions? Options for configuring the call's audio.
media.videoOptions call.VideoOptions? Options for configuring the call's video.
media.screenOptions call.ScreenOptions? Options for configuring the call's screenShare.
options Object? (default {})
options.bandwidth call.BandwidthControls? Options for configuring media's bandwidth.
options.dscpControls call.DSCPControls? Options for configuring DSCP markings on the media traffic

end

Ends an ongoing call.

The SDK will stop all local media associated with the call. Events will be emitted to indicate which media tracks were stopped. See the call:trackEnded event for more information.

The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:stateChange event locally when the operation completes. The remote participant will be notified, through their own call:stateChange event, that the call was ended.

end(callId: string)
Parameters
Name Description
callId string The ID of the call to end.

call:availableCodecs

The list of available and supported codecs by the browser have been retrieved.

This event is emitted as a result of the call.getAvailableCodecs API. Please refer to the API for more information.

call:availableCodecs
Parameters
Name Description
params Object
params.kind string The kind of media the codecs are for.
params.codecs Array<Object> The list of codecs.
Example
client.on('call:availableCodecs', function (codecs) {
   // Iterate over each codec.
   codecs.forEach(codec => {
       // Handle the data by analysing its properties.
       // Some codec instances may have the same name, but different characteristics.
       // (i.e. for a given audio codec, the number of suported channels may differ (e.g. mono versus stereo))
       ...
   })
})

call:mediaConnectionChange

A Call's media connection state has been changed.

This event is emitted as a result of changes to the media connection of the Call. These state changes occur during call establishment, connection loss/re-establishment, call completion, etc.

To check the media connection state of a call, retrieve the call's information using the call.getById API, and check the mediaConnectionState property of the call. See call.mediaConnectionStates for the list of possible values and descriptions.

call:mediaConnectionChange
Parameters
Name Description
params Object
params.callId string The ID of the Call whose media connection state was changed.
params.previous Object The call's media connection properties before the operation changed it.
params.previous.state string The previous state of the media connection.

call:mediaRestart

A media restart operation for a Call has been attempted.

This event is emitted as a result of the call.restartMedia API being called. See the description for call.restartMedia for information about its usage.

The call:mediaConnectionChange event will also be emitted alongside this event when the media restart operation is successful.

call:mediaRestart
Parameters
Name Description
params Object
params.callId string The ID of the Call that was acted on.
params.error api.BasicError? An error object, if the operation was not successful.
Example
client.on('call:mediaRestart', function (params) {
   if (params.error) {
     // The operation failed. May want to determine whether to re-attempt the
     //    operation (if the failure was simply a connectivity issue) or to
     //    consider the call's media irrecoverable.
     ...
   } else {
     // The call should be re-establishing media, with the call's
     //    `mediaConnectionState` being updated.
     const mediaState = client.call.getById(params.callId).mediaConnectionState
     ...
   }
})

call:newMedia

New media has been added to the call.

call:newMedia
Parameters
Name Description
params Object
params.callId string The ID of the call.
params.local boolean Whether the new media is local or not.
params.tracks Array The list of new Tracks.
params.mediaId string The ID of the Media object the Tracks belong to.

call:operation

A call operation has either started, been updated, or finished.

Information about ongoing call operations are stored on the CallObject. This event indicates that an operation's information has changed.

The status of an operation indicates whether the local or remote side of the call is currently processing it, with values being 'ONGOING' or 'PENDING', respectively. All operations will begin as 'ONGOING' status with an event indicating the 'START' transition. Operations that require a response from the remote side will have an 'UPDATE' transition to the 'PENDING' status once it starts to wait for the response. Once complete, an event will indicate a 'FINISH' transition and the operation will be removed from the call state.

call:operation
Parameters
Name Description
params Object
params.callId string The ID for the call being operated on.
params.operation string The type of operation causing this event.
params.operationId string The unique ID of the call operation.
params.transition string The transition reason for the operation change.
params.isLocal boolean Flag indicating whether the operation was local or not.
params.previous Object? The operation information before this change. If the transition is to "start" the operation, there will be no previous information.
params.previous.operation string? The operation that was ongoing.
params.previous.status string? The operation status before this change.
params.error api.BasicError? An error object, if the operation was not successful.
Example
client.on('call:operation', (params) => {
   const { callId, operationId } = params

   // Get the operation from the call's state that this event is about.
   const call = client.call.getById(callId)
   const operation = call.currentOperations.find(op => op.id === operationId)
   log(`${operation.type} operation is now ${operation.status} for call ${callId}.`)
})

call:receive

A new incoming call has been received.

Information about the Call can be retrieved using the call.getById API.

NOTE: Upon receiving this notification the call is in "Initiating" state. In order to answer calls, they must be in either "Ringing" or "Initiated" states. Therefore, this event should not be used to prompt the user to respond. Instead, the call:stateChange event should be used for this purpose.

call:receive
Parameters
Name Description
params Object
params.callId string The ID of the call.
params.error api.BasicError? An error object, if the operation was not successful.
Example
client.on('call:receive', function(params) {
    // We have received a call
    promptUser(client.call.getById(params.callId));
});

call:removedMedia

Media has been removed from the call.

call:removedMedia
Parameters
Name Description
params Object
params.callId string The ID of the call.
params.local boolean Whether the removed Media was local or not.
params.tracks Array The list of removed Tracks.

call:start

An outgoing call has been started.

Information about the Call can be retrieved using the call.getById API.

call:start
Parameters
Name Description
params Object
params.callId string The ID of the call.

call:stateChange

A Call's state has changed.

See call.states for information about call states.

call:stateChange
Parameters
Name Description
params Object
params.callId string The ID of the Media object that was operated on.
params.previous Object The call's properties before the operation changed it.
params.previous.state string The previous state of the call.
params.previous.localHold boolean? The previous local hold state. Present when the state change was a hold/unhold operation.
params.previous.remoteHold boolean? The previous remote hold state. Present when the state change was a hold/unhold operation.
params.transition Object? Contains more detailed information about the state change.
params.transition.statusCode number? The status code associated with the particular state change's reason.
params.transition.reasonText string? The reason for the state change.
params.error api.BasicError? An error object, if the operation was not successful.
Example
client.on('call:stateChange', function (params) {
    const call = client.call.getById(params.callId)
    const prevState = params.previous.state
    log(`Call changed from ${prevState} to ${call.state} state.`)

    // Handle the event depending on the new call state.
    switch (call.state) {
        case client.call.states.CONNECTED:
            // Handle being on call with media.
            break
        case client.call.states.ENDED:
            // Handle call ending.
            break
        ...
    }
})

call:statsReceived

Stats have been retrieved for a Call or specific Track of a Call.

See the call.getStats API for more information.

call:statsReceived
Parameters
Name Description
params Object
params.callId string The ID of the Call to retrieve stats for.
params.trackId string? The ID of the Track to retrieve stats for.
params.result Map? The RTCStatsReport.
params.error api.BasicError? An error object, if the operation was not successful.
Example
client.on('call:statsReceived', function (params) {
   if (params.error) {
     // Handle the error from the operation.
     const { code, message } = params.error
     ...
   } else {
     // Iterate over each individual statistic inside the RTCPStatsReport Map.
     // Handle the data on its own or collate with previously gathered stats
     //    for analysis.
     params.result.forEach(stat => {
       ...
     })
   }
})

call:trackReplaced

A local Track has been replaced by the call.replaceTrack API.

This event is a combination of a track being removed from the Call and a new track being added to the Call. The previous Track's media is no longer available, similar to the call:tracksRemoved event, and the new Track is available in its place, similar to the call:tracksAdded event. The event includes information about the Track that was replaced to help an application replace it seamlessly.

call:trackReplaced
Parameters
Name Description
params Object
params.callId string The ID of the call where a track was replaced.
params.newTrackId string? The ID of the new track that replaced the old track.
params.oldTrack call.TrackObject? State of the replaced track.
params.error api.BasicError? An error object, if the operation was not successful.
Example
client.on('call:trackReplaced', function (params) {
  const { callId, oldTrack, newTrackId } = params

  // Unrender the removed track.
  handleTrackGone(oldTrack, callId)

  // Render the added track.
  const track = client.media.getTrackById(newTrackId)
  handleTrackAdded(track, callId)
})

call:tracksAdded

Tracks have been added to the Call after an SDK operation. Both sides of the Call are now able to render these tracks.

Tracks are added to a Call when either the local or remote user adds new media to the Call, using the call.addMedia API for example, or when the Call is unheld with the call.unhold API.

Remote tracks are similarly added to a Call when new tracks are added by the remote user or either user unholds the call.

This event can indicate that multiple tracks have been removed by the same operation. For example, if the remote user added video to the call, this event would indicate a single, remote video track was added. If the local user unheld the call, this event would indicate that any tracks previously on the call have been re-added, both local and remote.

Information about a Track can be retrieved using the media.getTrackById API.

call:tracksAdded
Parameters
Name Description
params Object
params.callId string The ID of the Call the tracks were added to.
params.trackIds Array<string> List of track IDs that have been added to the Call.
Example
client.on('call:tracksAdded', function (params) {
   // Get the information for each track.
   const tracks = params.trackIds.map(client.media.getTrackById)
   tracks.forEach(track => {
     const { id, kind, isLocal } = track
     // Handle the track depending whether it is audio vs. video and local vs. remote.
     ...
   })
})

call:tracksRemoved

Tracks have been removed from the Call after an SDK operation. The tracks may still exist, but the media is not available to both sides of the Call any longer.

Tracks are removed from a Call when either the local or remote user stops the tracks, by using the call.removeMedia API for example, or when the Call is held with the call.hold API.

This event can indicate that multiple tracks have been removed by the same operation. For example, if the remote user removed video from the call, this event would indicate a single, remote video track was removed. If the local user held the call, this event would indicate that all tracks on the call have been removed, both local and remote.

Information about a Track can be retrieved using the media.getTrackById API.

call:tracksRemoved
Parameters
Name Description
params Object
params.callId string The ID of the Call the tracks were removed from.
params.trackIds Array<string> List of track IDs that have been removed from the Call.
Example
client.on('call:tracksRemoved', function (params) {
   // Get the information for each track.
   const tracks = params.trackIds.map(client.media.getTrackById)
   tracks.forEach(track => {
     const { id, kind, isLocal } = track
     // Handle the track depending whether it is audio vs. video and local vs. remote.
     ...
   })
})

getAll

Retrieves the information of all calls made during the current session.

getAll(): Array<call.CallObject>
Returns
Array<call.CallObject>: Call objects.
Example
let calls = client.call.getAll()
let currentCalls = calls.filter(call => {
    return call.state === client.call.states.CONNECTED
})

getAvailableCodecs

Retrieve the list of available and supported codecs based on the browser's capabilities for sending media.

This API will return a promise which, when resolved, it will contain the list of available and supported codecs. In addition, the SDK emits a call:availableCodecs event upon retrieving that list of codecs.

This API is a wrapper for the static method RTCRtpSender.getCapabilities().

getAvailableCodecs(kind: string): Promise
Parameters
Name Description
kind string The kind of media, i.e., 'audio' or 'video', to get the list of available codecs of.
Returns
Promise: A promise that will resolve with an object containing the available codecs, along with the kind parameter, that was supplied in the first place. If there was an error, it will return undefined.
Example
try {
   // The API will return a promise that resolves with the codecs.
   const result = await client.call.getAvailableCodecs('audio')
   result.forEach(codec => {
       // Inspect the codec supported by browser by looking at its properties.
       ...
   })
} catch (err) {
   // Handle the error.
   const { code, message } = err
   ...
}

getById

Retrieves the information of a single call with a specific call ID.

getById(callId: string): call.CallObject
Parameters
Name Description
callId string The ID of the call to retrieve.
Returns
call.CallObject: A call object.

getReport

Retrieve the call metrics report for a call.

The object returned from this API will be in JSON format. The top level object is the report and will include a timeline of events that were recorded during a call as well as a map object containing computed metrics.

Any event in a timeline will have it's own timeline that may have recorded events. Events in a timeline are scoped to that timelines event or report.

The report and some events may have additional data included in a data property.

See event documentation here. See metrics documentation here.

getReport(callId: string): Object
Parameters
Name Description
callId string The id of the call to retrieve the report on.
Returns
Object: An object containing all metrics and data tracked against this call.

getStats

Retrieve a snapshot of the low-level information of the Call through statistical report.

The data retrieved is a RTCStatsReport object, which contains many individual RTCStats. These are advanced statistics gathered by the browser providing insights into the Call at a certain point in time. Aggregating reports over a period of time would allow a low-level analysis of the Call for that period. As an example, this could be done to determine the media quality during the Call.

A Track ID can optionally be provided to get a report for a specific local Track of the Call.

This API will return a promise which, when resolved, will contain the report of the particular call. The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:statsReceived event, after the operation completes, that has the report.

getStats(callId: string, trackId: string?): Promise
Parameters
Name Description
callId string The ID of the Call to retrieve the report.
trackId string? ID of a local Track being used by the Call. If not provided, RTCStatsReport is generated for the Call itself.
Returns
Promise: A promise that will resolve with the stats report or an error if it fails.
Example
// Get a snapshot of the Call's stats.
//   This may be done on a regular interval to collect data over time.
try {
   // The API will return a promise that resolves with the stats.
   const result = await client.call.getStats(callId)
   result.forEach(stats => {
       // Handle the data on its own or collate with previously gathered stats
       //    for analysis.
       ...
   })
} catch (err) {
   // Handle the error.
   const { code, message } = err
   ...
}

hold

Puts a call on hold.

The specified call to hold must not already be locally held. Any/all media received from the remote participant will stop being received, and any/all media being sent to the remote participant will stop being sent.

Some call operations cannot be performed while the call is on hold. The call can be taken off hold with the call.unhold API.

The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:stateChange event locally when the operation completes. The remote participant will be notified of the operation through a call:stateChange event as well.

hold(callId: string)
Parameters
Name Description
callId string The ID of the call to hold.

mediaConnectionStates

Possible states that a Call's media connection can be in.

A Call's media connection state describes the current status of media within the call. An application should use this state to understand whether the Call participants are able to see/hear each other or may be experiencing connection issues. The media connection state can be used alongside the Call state to determine if media issues are occurring while the participants are expecting to be connected.

An important state to check for is the FAILED state. This state signifies that there is no media connection between the call participants and an action must be taken to resolve the problem. Using the call.restartMedia API will attempt to reconnect the media. See the call.restartMedia API description for more information.

These states are direct reflections of the possible RTCPeerConnection.iceConnectionState values.

The Call's media connection state is a property of the CallObject, which can be retrieved using the call.getById or call.getAll APIs.

The SDK emits a call:mediaConnectionChange event when a Call's media connection state changes from one state to another.

mediaConnectionStates

Type: Object

Properties
NEW (string) : The Call is initializing the local side of the connection and waiting on information from the remote side. When the information is received, the state will transition into checking as the Call automatically begins the connection process.
CHECKING (string) : The Call has received information from the remote endpoint and is working to establish the media connection. When finished, the state will transition to either connected or failed .
CONNECTED (string) : A usable connection has been made and the Call will now have media. The connection may not be optimal, though, so the Call will continue establishment to improve the connection before going into the completed state.
COMPLETED (string) : The media connection process has fully completed and the optimal connection has been established. While in this state, the Call endpoints will receive each other's media.
DISCONNECTED (string) : Media has become disconnected and the Call endpoints have stopped receiving each other's media. The Call will automatically attempt to reconnect, transitioning back to completed if successful or to failed if not.
FAILED (string) : The connection has failed and cannot be recovered automatically. A full media connection refresh is required to reestablish a connection. See the call.restartMedia API.
CLOSED (string) : The connection has been shut down and is no longer in use.
Example
// Use the media connection states to check the status of the media connection of the Call.
client.on('call:mediaConnectionChange', function (params) {
  // Retrieve the state of the Call this event is for.
  const call = client.call.getById(params.callId)
  const mediaConnectionStates = client.call.mediaConnectionStates

  // Check the mediaConnectionState to determine which scenario the call is in.
  switch (call.mediaConnectionState) {
    case mediaConnectionStates.CONNECTED:
    case mediaConnectionStates.COMPLETED:
      // Media established: The Call's media is connected. The Call's participants
      //    are able to see/hear each other.
      // These states will occur after Call establishment.
      ...
      break
    case mediaConnectionStates.NEW:
    case mediaConnectionStates.CHECKING:
    case mediaConnectionStates.DISCONNECTED:
      // Media pending: The Call's media is not connected. The Call is working
      //    to connect media automatically.
      // These states will occur during Call establishment and may occur midcall if there are
      //    connection issues (eg. poor network quality) or a Call participant has changed (eg. transfer).
      ...
      break
    case mediaConnectionStates.FAILED:
     // Media has failed. The call requires a media refresh to reestablish.
     // This state will occur after the `DISCONNECTED` state is encountered.
     ...
      break
    case mediaConnectionStates.CLOSED:
      // Media ended due to the Call being ended.
      // This state will occur after Call establishment.
      ...
      break
  }
}

metrics

List of metrics available as part of a Call Report. Metrics are calculated only for the successful scenarios.

As a call progresses, timings are calculated for the duration of operations and other events. They are recorded in a call report that can be retrieved via the call.getReport API.

metrics

Type: Object

Properties
CALL_DURATION (string) : The duration of a completed call starting from the make call API call or incoming call notification until the call ends.
MAKE_CALL_PRE_LOCAL_SETUP (string) : The amount of time it takes from when the make call operation starts up until right before we set local description.
MAKE_CALL_LOCAL_SETUP (string) : The amount of time it takes from when a call is made until the call is setup locally. This does not include any remote session creation.
MAKE_CALL_REMOTE_SETUP (string) : The amount of time it takes from when the create session request is sent until the SDK processes the response.
TIME_TO_MAKE (string) : For outgoing calls, the time for the make operation to complete.
ANSWER_CALL_LOCAL_SETUP (string) : The amount of time it takes from when the answer call operation starts until it is setup locally. (i.e. from the time an incoming call is answered until media is connected)
ANSWER_CALL_PRE_LOCAL_SETUP (string) : The amount of time it takes from when the answer call operation starts up until right before we set local description.
TIME_TO_ANSWER (string) : For incoming calls, the time for the answer operation to complete.
TIME_FROM_RECEIVE_TO_ANSWER (string) : For incoming calls, the time from the call first being received until it has been answered. Includes call processing and setup, as well as time for the answer API to have been called.
TIME_TO_CALL_SETUP_DURATION (string) : For incoming calls, the time from the call first being received until media is connected. Similar to TIME_FROM_RECEIVE_TO_ANSWER , but without the answer REST request.
TIME_TO_RINGING (string) : The amount of time it takes from when a call is made until the SDK recieves the remote ringing notification.
TIME_TO_IGNORE (string) : The amount of time it takes for the ignore call to complete.
TIME_TO_REJECT (string) : The amount of time it takes for the reject call to complete.
TIME_TO_ADD_MEDIA (string) : The amount of time it takes from when the local add media operation starts until it has finished.
TIME_TO_ADD_MEDIA_REMOTE (string) : The amount of time it takes from when the SDK receives a remote add media notification until it is handled and operation completes.
TIME_TO_REMOVE_MEDIA (string) : The amount of time it takes from when the local remove media operation starts until it has finished.
TIME_TO_REMOVE_MEDIA_REMOTE (string) : The amount of time it takes from when the SDK receives a remote remove media notification until it is handled and operation completes.
TIME_TO_RESTART_MEDIA (string) : The amount of time it takes from when the restart media operation starts until it has finished.
TIME_TO_HOLD_LOCAL (string) : The amount of time it takes from when the local hold operation starts until it has finished.
TIME_TO_HOLD_REMOTE (string) : The amount of time it takes from when the SDK receives a remote hold notification until it is handled and operation completes.
TIME_TO_UNHOLD_LOCAL (string) : The amount of time it takes from when the local unhold operation starts until it has finished.
TIME_TO_UNHOLD_REMOTE (string) : The amount of time it takes from when the SDK receives a remote unhold notification until it is handled and operation completes.
TIME_TO_COLLECT_ICE_CANDIDATES (string) : The amount of time it takes from when the local description is set to when all ICE candidates have been collected.
TIME_TO_RELAY_CANDIDATES (string) : The amount of time it takes from when the ice collection operation starts until each relay candidate has been recieved.
TIME_TO_SEND_CUSTOM_PARAMETERS (string) : The amount of time it takes from when the send custom parameters operation starts until it has finished.
TIME_TO_FORWARD (string) : The amount of time it takes from when the forward call operation starts until it has finished.
TIME_TO_DIRECT_TRANSFER (string) : The amount of time it takes from when the direct transfer operation starts until it has finished.
TIME_TO_CONSULTATIVE_TRANSFER (string) : The amount of time it takes from when the consultative transfer operation starts until it has finished.
TIME_TO_JOIN (string) : The amount of time it takes from when the join call operation starts until it has finished.
Example
const report = client.call.getReport(callId)
const callDuration = report.metrics.find(metric => metric.type === client.call.metrics.CALL_DURATION)
log(`Call duration was ${callDuration.data}ms.`)

playAudioFile

Plays an audio file to the remote side of the Call. This API will temporarily replace the Call's local audio track with an audio file for the duration of the audio file.

The Call must be in Connected state and have a local audio track for this operation.

This API will not affect media other than the local audio track. Other media on the Call, such as local video or remote audio, can be muted or unrendered during this operation if desired.

This operation will use the browser's Audio constructor to read in the audio file. The filePath parameter will be used directly with Audio, so can be either a relative file path to your audio file or a URL pointing to a file.

This API returns a promise that can be used to track the progress of the operation. The promise will resolve after the operation completes or reject if an error is encountered. Additionally, an extra onPlaying callback is provided on the Promise to indicate when the audio file actually begins to play. See the code example below for a sample.

The SDK will emit call:operation events locally as the operation progresses. The remote endpoint will not receive an event for this operation.

If an error is encountered during the operation and the SDK is unable to replace the original local audio track, then that track will be forcibly ended and an media:trackEnded event will be emitted for it. This will release the microphone and avoid losing access to the track while it is active, allowing the application to resolve the scenario by using the call.replaceTrack API to revert the local audio track.

playAudioFile(callId: string, filePath: string): Promise
Parameters
Name Description
callId string The ID of the Call to act on.
filePath string The path to the audio file.
Returns
Promise: Promise that resolves when the operation is complete.
Example
// The API returns a promise which will provide feedback about the operation.
client.call.playAudioFile(callId, filePath)
   .then(() => {
     // Audio file has finished playing; call has reverted to previous audio.
   })
   .catch(err => {
     // An error has occurred during the operation.
   })

// The returned promise can optionally provide feedback midway through the
//   operation. A chainable `onPlaying` method denotes when the audio file has
//   started to play and the Call's audio has been replaced.
client.call.playAudioFile(callId, filePath)
   .onPlaying(({ duration }) => {
     // Audio file has started playing; call audio is now the file.
     // Note: Calling `onPlaying` must be done before `then` and `catch` for it
     //    to be chainable.
   })
   .then(() => { ... })
   .catch(err => { ... })

removeMedia

Remove tracks from an ongoing call.

The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:trackEnded event for both the local and remote users to indicate that a track has been removed.

removeMedia(callId: string, tracks: Array, options: Object?)
Parameters
Name Description
callId string The ID of the call to remove media from.
tracks Array A list of track IDs to remove.
options Object? (default {})
options.bandwidth call.BandwidthControls? Options for configuring media's bandwidth.

replaceTrack

Replace a call's track with a new track of the same media type.

The operation will remove the old track from the call and add a new track to the call. This effectively allows for changing the track constraints (eg. device used) for an ongoing call.

Because it completely replaces an old track with a new one, the old track's state characteristics are not carried over in the new track's state. (e.g. if an old track's state was 'muted' and replacement of this track has occured, the new track's state will be 'unmuted', as this is its default state)

The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:trackReplaced event locally when the operation completes. The newly added track will need to be handled by the local application. The track will be replaced seamlessly for the remote application, which will not receive an event.

replaceTrack(callId: string, trackId: string, media: Object)
Parameters
Name Description
callId string The ID of the call to replace the track of.
trackId string The ID of the track to replace.
media Object (default {}) The media options.
media.audio boolean (default false) Whether to create an audio track.
media.audioOptions call.AudioOptions? Options for configuring the audio track.
media.video boolean (default false) Whether to create a video track.
media.videoOptions call.VideoOptions? Options for configuring the video track.
media.screen boolean (default false) Whether to create a screen share track.
media.screenOptions call.ScreenOptions? Options for configuring the call's screenShare.
media.medias Array<media.DetachedMedia>? The detached media containing the track to be attached to this call. Though this parameter is an array for consistency with other APIs, it should only contain one entry.
Example
const callId = ...
// Get the video track used by the call.
const videoTrack = ...

// Replace the specified video track of the call with a new
//    video track.
client.call.replaceTrack(callId, videoTrack.id, {
  // The track should be replaced with a video track using
  //    a specific device. This effectively changes the input
  //    device for an ongoing call.
  video: true,
  videoOptions: {
    deviceId: cameraId
  }
})
const callId = ...
// Get the video track used by the call.
const videoTrack = ...

// Can also replace the specified video track of the call with a new
// screen sharing track because screen sharing is delivered as a video stream to remote peer.
// User will then be prompted to pick a specific screen to share and thus the device id will be selected.
client.call.replaceTrack(callId, videoTrack.id, {
  // The track should be replaced with a screen sharing track.
  // Note that 'screenOptions' property is not mandatory, as API will use default values
  // for properties like: width, height, frameRate.
  screen: true
})

reportEvents

Events used in the SDK's call reports.

As a call progresses, the operation(s)/function(s) being performed throughout the duration of a call are recorded as events in a call report. The call report can be retrieved via the call.getReport API. An application can use these event names to find the associated event(s) in the call report for more information on the event. See Call Reports tutorial for more information on call reports and events.

reportEvents

Type: Object

Properties
MAKE (string) : Starts when the make operation starts. Ends when the make operation finishes.
SEND_RINGING_FEEDBACK (string) : Starts when the send ringing feedback operation starts. Ends when the ringing feedback operation finishes.
RECEIVE_CALL (string) : Starts when the SDK receives a call and ends when the incoming call is setup.
REMOTE_RINGING (string)
ANSWER (string) : Starts when the answer operation starts. Ends when the answer operation finishes.
GET_USER_MEDIA (string) : Starts when user media is requested from the browser and ends when the media is created.
PROCESS_MEDIA_LOCAL (string) : Starts when the local media begins processing, and ends when the offer is set and ice collection completes.
PROCESS_MEDIA_REMOTE (string) : Starts when the remote response is received, and ends when the remote media is set.
ICE_COLLECTION (string) : Starts when ice candidate collection starts and ends when collection is complete.
RELAY_CANDIDATE_COLLECTED (string) : Starts and ends when a relay candidate is collected. Event data contains info on the candidate.
IGNORE (string) : Starts when the ignore operation starts. Ends when the ignore operation finishes.
REJECT (string) : Starts when the reject operation starts. Ends when the reject operation finishes.
FORWARD_CALL (string) : Starts when the forward call operation starts. Ends when the forward operation finishes.
END_LOCAL (string) : Starts when the end operation starts. Ends when the end operation finishes.
END_REMOTE (string) : Starts when the call status update ended operation starts. Ends when the call status update ended operation finishes.
ADD_BASIC_MEDIA (string) : Starts when the add basic media operation starts. Ends when the add basic media operation finishes.
ADD_MEDIA_LOCAL (string) : Starts when the add media operation starts. Ends when the add media operation finishes.
ADD_MEDIA_REMOTE (string) : Starts when a remote add media notification is received and ends when the operation is handled.
REMOVE_BASIC_MEDIA (string) : Starts when the remove basic media operation starts. Ends when the remove basic operation finishes.
REMOVE_MEDIA (string) : Starts when the remove media operation starts. Ends when the remove media operation finishes.
REMOVE_MEDIA_REMOTE (string) : Starts when a remote remove media notification is received and ends when the operation is handled.
MEDIA_RESTART (string) : Starts when the media restart operation starts. Ends when the media restart operation finishes.
REPLACE_TRACK (string) : Starts when the replace track operation starts. Ends when the replace track operation finishes.
HOLD_LOCAL (string) : Starts when the hold operation starts. Ends when the hold operation finishes.
HOLD_REMOTE (string) : Starts when a remote hold notification is received and ends when the operation is handled.
UNHOLD_LOCAL (string) : Starts when the unhold operation starts. Ends when the unhold operation finishes.
UNHOLD_REMOTE (string) : Starts when a remote unhold notification is received and ends when the operation is handled.
REST_REQUEST (string) : Starts when a REST request is to be made for an operation and ends when a response is received, or it times out.
PLAY_AUDIO (string) : Starts when the play audio operation starts. Ends when the play audio operation finishes.
START_MOH (string) : Starts when the start music on hold operation starts. Ends when the start music on hold operation finishes.
STOP_MOH (string) : Starts when the stop music on hold operation starts. Ends when the stop music on hold operation finishes.
SEND_CUSTOM_PARAMETERS (string) : Starts when the send custom parameters operation starts. Ends send custom parameters operation finishes.
GET_STATS (string) : Starts when the get stats operation starts. Ends when the get stats operation finishes.
SEND_DTMF (string) : Starts when the send DTMF operation starts. Ends when the DTMF operation finishes.
RESYNC (string) : Starts when the resync operation starts. Ends when the resync operation finishes.
DIRECT_TRANSFER (string) : Starts when the direct transfer operation starts. Ends when the direct transfer operation finishes.
CONSULTATIVE_TRANSFER (string) : Starts when the consultative transfer operation starts. Ends when the consultative transfer operation finishes.
JOIN (string) : Starts when the join operation starts. Ends when the join operation finishes.
GET_AVAILABLE_CODECS (string) : Starts when the get available codecs operation starts. Ends when the get available codecs operation finishes.
SLOW_START (string) : Starts when the slow start operation starts. Ends when the slow stop operation finishes.
Example
const report = client.call.getReport('callId')
const getAvailableCodecsEvent = report.timeline.find(event => event.type === client.call.reportEvents.GET_AVAILABLE_CODECS)
log(`Took ${getAvailableCodecsEvent.end - getAvailableCodecsEvent.start}ms to get available codecs.`)

restartMedia

Attempt to re-establish a media connection for a call.

This API will perform a "refresh" operation on the call with the intention of resolving media issues that may have been encountered. This API is only necessary after the Call's mediaConnectionState has entered the failed state, but may be used in other scenarios.

After the operation completes successfully, the Call will be re-establishing its media connection. By this time, or shortly after, the Call's mediaConnectionState should have transitioned to checking (via a call:mediaConnectionChange event) to signify the re-establishment. It will then transition to either connected or failed state, similar to during the initial Call establishment.

If this operation fails, then the Call will not attempt the re-establishment and will remain in the failed mediaConnectionState.

Behaviour during the operation may differ slightly based on the browser. Notably, Firefox will always transition to the checking mediaConnectionState no matter what the previous state was. Whereas Chrome will skip the checking state, transitioning directly to either connected or failed. This has the implication for Chrome that if the state does not change (for example, the Call is in the failed state before the media restart operation, and media re-establishment fails), then there will be no call:mediaConnectionChange event emitted. For this reason, Chrome-based applications may need a short delay after receiving the call:mediaRestart event before checking the Call's updated mediaConnectionState to ensure the application is acting on the "latest" state.

The SDK will emit a call:mediaRestart event when the operation completes.

The progress of the operation will be tracked via the call:operation event.

restartMedia(callId: string)
Parameters
Name Description
callId string The ID of the call to act on.

sendCustomParameters

Send the custom parameters stored as part of an ongoing call to the Gateway. The server may either consume the headers or relay them to another endpoint, depending on configuration.

Custom parameters are set on a call using the call.setCustomParameters API.

A Call's custom parameters are stored on the CallObject, which can be retrieved using the call.getById or call.getAll APIs.

sendCustomParameters(callId: string)
Parameters
Name Description
callId string The ID of the call being acted on.

sendDTMF

Send DTMF tones to a call's audio.

The provided tone can either be a single DTMF tone (eg. '1') or a sequence of DTMF tones (eg. '123') which will be played one after the other.

The specified call must be either in Connected, Ringing, or Early Media state, otherwise invoking this API will have no effect.

The tones will be sent as out-of-band tones if supported by the call, otherwise they will be added in-band to the call's audio.

The progress of the operation will be tracked via the call:operation event.

sendDTMF(callId: string, tone: string, duration: number, intertoneGap: number)
Parameters
Name Description
callId string ID of the call being acted on.
tone string DTMF tone(s) to send. Valid characters are ['0','1','2','3','4','5','6','7','8','9','#','*' and ','].
duration number (default 100) The amount of time, in milliseconds, that each DTMF tone should last.
intertoneGap number (default 70) The length of time, in milliseconds, to wait between tones.

setCustomParameters

Set the Custom Parameters of a call, to be provided to the remote endpoint.

The provided parameters will be saved as part of the call data, to be used throughout the duration of the call. All subsequent call operations will include these custom parameters. Therefore, invalid parameters, or parameters not previously configured on the server, will cause subsequent call operations to fail. See Custom Parameters for more information on constraints.

A Call's custom parameters are stored on the CallObject, which can be retrieved using the call.getById or call.getAll APIs.

The call.sendCustomParameters API can be used to send the custom parameters as a stand-alone REST request, rather than as part of a call operation.

Custom parameters can be removed from a call's information by setting them as undefined (e.g., call.setCustomParameters(callId)). Subsequent call operations will then no longer send the custom parameters.

setCustomParameters(callId: string, customParameters: (Array<call.CustomParameter> | undefined)): undefined
Parameters
Name Description
callId string The ID of the call.
customParameters (Array<call.CustomParameter> | undefined) The custom parameters to set.
Returns
undefined:
Example
// Set custom parameters on a call.
client.call.setCustomParameters(callId, [
   {
     name: 'Custom-Header',
     value: 'Custom Value'
   }
])

setSdpHandlers

Set SDP Handler Functions that will be run as part of a pipeline for all future calls. This will replace any SDP Handlers that were previously set.

SDP handlers can be used to make modifications to the SDP (e.g., removing certain codecs) before they are processed or sent to the other side.

This is an advanced feature, changing the SDP handlers mid-call may cause unexpected behaviour in future call operations for that call.

setSdpHandlers(sdpHandlers: Array<call.SdpHandlerFunction>): undefined
Parameters
Name Description
sdpHandlers Array<call.SdpHandlerFunction> The list of SDP handler functions to modify SDP.
Returns
undefined:

startVideo

Adds local video to an ongoing Call, to start sending to the remote participant.

Can only be used in a basic media scenario, where the Call does not already have video. For more advanced scenarios, the call.addMedia API can be used.

The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:tracksAdded event both for the local and remote users to indicate a track has been added to the Call.

startVideo(callId: string, videoOptions: call.VideoOptions?, options: Object?)
Parameters
Name Description
callId string ID of the call being acted on.
videoOptions call.VideoOptions? Options for configuring the call's video.
options Object?
options.bandwidth call.BandwidthControls? Options for configuring media's bandwidth.
options.dscpControls call.DSCPControls? Options for configuring DSCP markings on the media traffic.

states

Possible states that a Call can be in.

A Call's state describes the current status of the Call. An application should use the state to understand how the Call, and any media associated with the Call, should be handled. Which state the Call is in defines how it can be interacted with, as certain operations can only be performed while in specific states, and tells an application whether the Call currently has media flowing between users. Unless stated otherwise, the Call's state pertains to both caller & callee.

The Call's state is a property of the CallObject, which can be retrieved using the call.getById or call.getAll APIs.

The SDK emits a call:stateChange event when a Call's state changes from one state to another.

states

Type: Object

Properties
INITIATING (string) : The (outgoing) call is being started. While in this state, no Call operations can be performed until Call gets into Initiated state.
INITIATED (string) : A call has been started and both the callee and caller may now perform further operations on the call object.
RINGING (string) : The call has been received by both parties, and is waiting to be answered.
EARLY_MEDIA (string) : The call has not been answered, but media is already being received. This may be network-ringing media, IVR system media, or other pre-answer medias. When early media is supported, this state may replace the Ringing state. This is a state valid only for caller's side.
CANCELLED (string) : The call was disconnected before it could be answered. This is a state valid only for callee's side.
CONNECTED (string) : Both parties are connected and media is flowing.
ON_HOLD (string) : Both parties are connected but no media is flowing.
ENDED (string) : The call has ended.
Example
// Use the call states to know how to handle a change in the call.
client.on('call:stateChange', function (params) {
   const call = client.call.getById(params.callId)
   // Check if the call now has media flowing.
   if (call.state === client.call.states.CONNECTED) {
     // The call is now active, and can perform midcall operations.
   }
})

stopVideo

Removes local video from an ongoing Call, stopping it from being sent to the remote participant.

Can only be used in a basic media scenario, where the Call has only one video track. For more advanced scenarios, the call.removeMedia API can be used.

The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:tracksRemoved event for both the local and remote users to indicate that a track has been removed.

stopVideo(callId: string)
Parameters
Name Description
callId string ID of the call being acted on.

unhold

Takes a call off hold.

The specified call to unhold must be locally held. If the call is not also remotely held, call media will be reconnected as it was before the call was held.

The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:stateChange event locally when the operation completes. The remote participant will be notified of the operation through a call:stateChange event as well.

unhold(callId: string)
Parameters
Name Description
callId string The ID of the call to unhold.

api

The 'api' is the type returned by the create function. It contains various top-level functions that pertain to SDK global instance as well as several nested namespaces that pertain to various features (e.g. call, contacts, presence, etc).

api
Types
BasicError
Functions
getVersion()
destroy()
getConfig()
updateConfig(newConfigValues)
on(type, listener)
off(type, listener)
subscribe(listener)
unsubscribe(listener)
getBrowserDetails()
getUserInfo()
Events
request:error

connection

The 'connection' namespace is used to connect and maintain connections between the SDK and one or more backend servers.

connection
Types
WSConnectionObject
Functions
getSocketState()
enableConnectivityChecking(enable)
resetConnection()
Events
ws:change

logger

The SDK has an internal logging system for providing information about its behaviour. The SDK will generate logs, at different levels for different types of information, which are routed to a "Log Handler" for consumption. An application can provide their own Log Handler (see config.logs) to customize how the logs are handled, or allow the default Log Handler to print the logs to the console.

The SDK's default Log Handler is merely a thin wrapper around the browser's console API (ie. window.console). It receives the log generated by the SDK, called a "Log Entry", formats a human-readable message with it, then uses the console to log it at the appropriate level. This is important to be aware of, since your browser's console may affect how you see the SDK's default log messages. Since the default Log Handler uses the console's levels, the browser may filter which messages are shown depending on which levels it has configured. For a user that understands console log levels, this can be helpful for filtering the logs to only the relevant information. But it can equally be a hindrance by hiding the more detailed log messages (at the 'debug' level), since browser can have this level hidden by default. For this reason, we recommend providing a custom Log Handler to the SDK that is better suited for your application and its users.

logger
Types
LogEntry
LogHandler(LogEntry)
Functions
levels()

makeAnonymous

Starts an outgoing call as an anonymous user.

The call will be tracked by a unique ID that is returned by the API. The application will use this ID to identify and control the call after it has been initiated.

The call.getById API can be used to retrieve the current information about the call.

The progress of the operation will be tracked via the call:operation event.

The SDK will emit a call:start event locally when the operation completes. When the remote participant receives the call, a call:receive event will be emitted remotely for them.

The SDK requires access to the machine's media devices (eg. microphone) in order to make a call. If it does not already have permissions to use the devices, the user may be prompted by the browser to give permissions.

Detached media can be used when starting a call. Detached media is created locally outside of a call and must be managed by the application. It can be used when making a call by passing an array of detached track ids in the media object. You can start a call with a mixture of detached and requested media, however, you can only use one of each type (audio, video, screen). For example, you could include a detached track id for video, and set MediaConstraint.audio: true, but you can't set MediaConstraint.video: true if you have passed in a detached track id of kind video.

makeAnonymous(callee: string, credentials: Object, callOptions: Object): string
Parameters
Name Description
callee string Full user ID of the call recipient.
credentials Object Information needed to validate a token anonymous call.
credentials.realm Object The realm used to encrypt the tokens.
credentials.accountToken Object? The encrypted account token of the account making the call.
credentials.fromToken Object? The encrypted SIP address of the account/caller.
credentials.toToken Object? The encrypted SIP address of the callee.
credentials.authAccount Object? The account used to authenticate if no token is provided.
callOptions Object Call options.
callOptions.from string This identifies the anonymous caller, as seen by the callee. If the caller has a registered account and it's subscribed to backend at the time of the anonymous call is made, then its value must use the username@domain format. Otherwise, in most cases, the value can be any display name that the anonymous user wants to use when making the call.
callOptions.audio Boolean (default true) Whether the call should have audio on start. Currently, audio-less calls are not supported.
callOptions.audioOptions Object? Options for configuring the call's audio.
callOptions.audioOptions.deviceId call.MediaConstraint? ID of the microphone to receive audio from.
callOptions.bandwidth call.BandwidthControls? Options for configuring media's bandwidth.
callOptions.video Boolean (default false) Whether the call should have video on start.
callOptions.videoOptions Object? Options for configuring the call's video.
callOptions.videoOptions.deviceId call.MediaConstraint? ID of the camera to receive video from.
callOptions.videoOptions.height call.MediaConstraint? The height of the video.
callOptions.videoOptions.width call.MediaConstraint? The width of the video.
callOptions.videoOptions.frameRate call.MediaConstraint? The frame rate of the video.
callOptions.medias Array<media.DetachedMedia>? List of detached medias containing tracks to be attached to this call.
callOptions.screen Boolean (default false) Whether the call should have screenshare on start.
callOptions.screenOptions Object? Options for configuring the call's screenShare.
callOptions.screenOptions.height call.MediaConstraint? The height of the screenShare.
callOptions.screenOptions.width call.MediaConstraint? The width of the screenShare.
callOptions.screenOptions.frameRate call.MediaConstraint? The frame rate of the screenShare.
callOptions.displayName string? Custom display name to be provided to the destination. Only used with token-less anonymous calls. Not supported in all environments and may use default display name.
callOptions.customParameters Array<call.CustomParameter>? Custom SIP header parameters for the SIP backend.
Returns
string: Id of the outgoing call.
Example
// Make a basic anonymous call.
let callee = 'user1@example.com';
let callOptions = { ... };

let callId = client.call.makeAnonymous(callee, {}, callOptions);
// Make a time-limited token anonymous call.
let callee = 'user1@example.com';
let account = 'user2@example.com';
let callOptions = { ...
    customParameters: [
      {
        "name": "X-GPS",
        "value": "42.686032,23.344565"
      }
    ],
    ...
  };

// Generate / Retrieve the encrypted tokens.
const key = 'abc123...';
const credentials = {
     accountToken: createToken(account, key),
     fromToken: createToken('sip:' + account, key),
     toToken: createToken('sip:' + callee, key),
     realm: 'realmAbc123...'
};

let callId = client.call.makeAnonymous(callee, credentials, callOptions);

media

The 'media' namespace provides an interface for interacting with Media that the SDK has access to. Media is used in conjunction with the Calls feature to manipulate and render the Tracks sent and received from a Call.

Media and Track objects are not created directly, but are created as part of Call operations. Media and Tracks will either be marked as "local" or "remote" depending on whether their source is the local user's machine or a remote user's machine.

The Media feature also keeps track of media devices that the user's machine can access. Any media device (eg. USB headset) connected to the machine can be used as a source for media. Available devices can be found using the media.getDevices API.

media
Types
DetachedMedia
Functions
getDevices()
getById(mediaId)
getTrackById(trackId)
createLocalMedia(mediaConstraints)
getLocalMedia()
disposeLocalMedia(localMedia)
initializeDevices(constraints?)
renderTracks(trackIds, cssSelector, options?)
muteTracks(trackIds)
unmuteTracks(trackIds)
removeTracks(trackIds, cssSelector)
Events
devices:change
devices:error
media:muted
media:unmuted
media:sourceMuted
media:sourceUnmuted
media:trackRendered
media:trackEnded

notification

The 'notification' namespace allows user to register/deregister for/from push notifications as well as enabling/disabling the processing of websocket notifications.

notification
Functions
process(notification, channel)
Events
notifications:change
notifications:error

request

The 'request' namespace (within the 'api' type) is used to make network requests to the server.

request
Functions
fetch(resource, init)

sdpHandlers

A set of SdpHandlerFunctions for manipulating SDP information. These handlers are used to customize low-level call behaviour for very specific environments and/or scenarios.

Note that SDP handlers are exposed on the entry point of the SDK. They can be added during initialization of the SDK using the config.call.sdpHandlers configuration parameter. They can also be set after the SDK's creation by using the call.setSdpHandlers function.

sdpHandlers
Example
import { create, sdpHandlers } from '@rbbn/webrtc-js-sdk';
const codecRemover = sdpHandlers.createCodecRemover(['VP8', 'VP9'])
const client = create({
  call: {
    sdpHandlers: [ codecRemover, <Your-SDP-Handler-Function>, ...]
  }
})
// Through the Call API post-instantiation
client.call.setSdpHandlers([ codecRemover, <Your-SDP-Handler-Function>, ...])
Types
CodecSelector
Functions
createCodecRemover(codecs)