0% found this document useful (0 votes)
7K views78 pages

LTRT-14054 WebRTC Web Browser Client SDK API Reference Guide Ver. 1.15

This document provides an overview of an API reference guide for AudioCodes WebRTC solutions. It describes the purpose and scope of the guide, as well as the benefits of WebRTC. It also outlines the main API classes for AudioCodesUA and AudioCodesSession and their standard and advanced methods.

Uploaded by

erika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7K views78 pages

LTRT-14054 WebRTC Web Browser Client SDK API Reference Guide Ver. 1.15

This document provides an overview of an API reference guide for AudioCodes WebRTC solutions. It describes the purpose and scope of the guide, as well as the benefits of WebRTC. It also outlines the main API classes for AudioCodesUA and AudioCodesSession and their standard and advanced methods.

Uploaded by

erika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 78

API Reference Guide

AudioCodes WebRTC Solutions for Enterprises

WebRTC Web Browser Client

Version 1.15
API Reference Guide Contents

Table of Contents
1 Introduction 12
1.1 Purpose................................................................................................................. 12
1.2 Scope.................................................................................................................... 12
1.3 Benefits................................................................................................................. 12
2 API Classes 14
2.1 AudioCodesUA......................................................................................................14
2.1.1 Standard Methods.................................................................................................. 16

2.1.1.1 constructor.............................................................................................. 16
2.1.1.2 init........................................................................................................... 16
2.1.1.3 setServerConfig......................................................................................16
2.1.1.4 setAccount.............................................................................................. 17
2.1.1.5 login........................................................................................................ 17
2.1.1.6 logout...................................................................................................... 17
2.1.1.7 setListeners............................................................................................. 17
2.1.1.8 call........................................................................................................... 18
2.1.2 Advanced Methods.................................................................................................19

2.1.2.1 setRegisterExtraHeaders........................................................................19
2.1.2.2 call........................................................................................................... 19
2.1.2.3 setUseSessionTimer...............................................................................20
2.1.2.4 setRegisterExpires..................................................................................20
2.1.2.5 isInitialized.............................................................................................. 20
2.1.2.6 version.................................................................................................... 20
2.1.2.7 setChromeAudioConstraints...................................................................21
2.1.2.8 setConstraints......................................................................................... 21
2.1.2.9 setBrowsersConstraints..........................................................................23
2.1.2.10 setUserAgent.......................................................................................... 24
2.1.2.11 setAcLogger............................................................................................ 24
2.1.2.12 setJsSipLogger.......................................................................................24
2.1.2.13 setWebSocketKeepAlive.........................................................................25
2.1.2.14 setReconnectIntervals.............................................................................27
2.1.2.15 deinit....................................................................................................... 27
2.1.2.16 setDtmfOptions.......................................................................................27
2.1.2.17 setOAuthToken.......................................................................................28
2.1.2.18 setEnableAddVideo.................................................................................28
2.1.2.21 checkAvailableDevices...........................................................................29
2.1.2.22 getWR().stream.getInfo...........................................................................29
2.1.2.23 getWR().connection.getTransceiversInfo................................................30
2.1.2.25 sendMessage.......................................................................................... 30
2.1.2.26 setModes................................................................................................ 31
2.1.2.27 getNumberOfSBC...................................................................................33
2.1.2.28 switchSBC............................................................................................... 33
2.1.2.29 openScreenSharing................................................................................34
2.1.2.30 closeScreenSharing................................................................................35
2.1.2.31 isScreenSharingSupported.....................................................................35
2.1.2.32 setNetworkPriority...................................................................................35
2.1.2.33 subscribe................................................................................................. 35
2.1.2.34 notify....................................................................................................... 36
2.2 AudioCodesSession..............................................................................................37
2.2.1 Standard Methods.................................................................................................. 38

2.2.1.1 answer.................................................................................................... 38
2.2.1.2 reject....................................................................................................... 38
2.2.1.3 redirect.................................................................................................... 39

Version 1.15 3 WebRTC


WebRTC Web Browser Client

2.2.1.4 terminate................................................................................................. 39
2.2.1.5 muteAudio............................................................................................... 40
2.2.1.6 muteVideo............................................................................................... 40
2.2.1.7 isAudioMute............................................................................................ 40
2.2.1.8 isVideoMute............................................................................................ 40
2.2.1.9 sendDTMF.............................................................................................. 41
2.2.1.10 isOutgoing............................................................................................... 41
2.2.1.11 data: map<String, Object>......................................................................41
2.2.1.12 duration................................................................................................... 42
2.2.1.13 wasAccepted........................................................................................... 42
2.2.1.14 isLocalHold............................................................................................. 42
2.2.1.15 isRemoteHold.......................................................................................... 43
2.2.1.16 IsReadyToReOffer..................................................................................43
2.2.1.17 hold......................................................................................................... 43
2.2.2 Advanced Methods.................................................................................................44

2.2.2.1 answer.................................................................................................... 44
2.2.2.2 reject....................................................................................................... 44
2.2.2.3 redirect.................................................................................................... 44
2.2.2.4 getReplacesHeader................................................................................45
2.2.2.5 getRTCPeerConnection..........................................................................45
2.2.2.6 getRTCLocalStream................................................................................45
2.2.2.7 getRTCRemoteStream............................................................................46
2.2.2.8 startSendingVideo...................................................................................46
2.2.2.9 stopSendingVideo...................................................................................47
2.2.2.10 hasVideo, hasSendVideo, hasReceiveVideo..........................................47
2.2.2.11 getVideoStatus........................................................................................ 47
2.2.2.12 hasEnabledSendVideo, hasEnabledReceiveVideo.................................48
2.2.2.13 getEnabledVideoStatus...........................................................................48
2.2.2.14 setRemoteHoldState...............................................................................48
2.2.2.15 sendRefer............................................................................................... 49
2.2.2.16 sendReInvite........................................................................................... 49
2.2.2.17 sendInfo.................................................................................................. 49
2.2.2.18 startScreenSharing.................................................................................50
2.2.2.19 stopScreenSharing..................................................................................50
2.2.2.20 isScreenSharing......................................................................................50
2.2.2.21 doesScreenSharingReplaceCamera.......................................................50
2.3 Subscriber............................................................................................................. 51
2.3.1 get state................................................................................................................. 51

2.3.2 get id...................................................................................................................... 51

2.3.3 subscribe................................................................................................................ 51

2.3.4 terminate................................................................................................................ 52

2.3.5 on........................................................................................................................... 52

2.3.6 removeAllListeners................................................................................................. 53

2.4 Notifier................................................................................................................... 54
2.4.1 get state................................................................................................................. 54

2.4.2 get id...................................................................................................................... 54

2.4.3 start........................................................................................................................ 54

2.4.4 setActiveState........................................................................................................ 55

API Reference Guide 4 Document, #, LTRT-14054


API Reference Guide Contents

2.4.5 notify....................................................................................................................... 55

2.4.6 terminate................................................................................................................ 55

2.4.7 on........................................................................................................................... 55

2.4.8 removeAllListeners................................................................................................. 56

2.5 BoadsoftAcdAgent................................................................................................57
2.5.1 constructor.............................................................................................................. 57

2.5.2 setListeners............................................................................................................ 57

2.5.3 setLog.................................................................................................................... 57

2.5.4 setAccount.............................................................................................................. 58

2.5.5 setLoginState......................................................................................................... 58

2.5.6 start........................................................................................................................ 58

2.5.7 stop........................................................................................................................ 58

2.5.8 logon...................................................................................................................... 59

2.5.9 logoff...................................................................................................................... 59

2.5.10 setState.................................................................................................................. 59

3 API Callbacks / Listeners Interfaces 60


3.1 Standard Callbacks...............................................................................................60
3.1.1 Login State Changed Event....................................................................................60

3.1.2 Incoming Call Event...............................................................................................60

3.1.3 Call Confirmed........................................................................................................ 60

3.1.4 Call Terminated...................................................................................................... 61

3.1.5 Outgoing Call Progress.......................................................................................... 61

3.1.6 Call Show Streams.................................................................................................61

3.2 Advanced Callbacks..............................................................................................62


3.2.1 Incoming call event.................................................................................................62

3.2.2 Call Confirmed........................................................................................................ 62

3.2.3 Call Terminated...................................................................................................... 63

3.2.4 Outgoing Call Progress.......................................................................................... 63

3.2.5 callHoldStateChanged............................................................................................63

3.2.6 callIncomingReinvite..............................................................................................64

3.2.7 transferorNotification.............................................................................................. 64

Version 1.15 5 WebRTC


WebRTC Web Browser Client

3.2.8 transfereeRefer...................................................................................................... 64

3.2.9 transfereeCreatedCall............................................................................................65

3.2.10 incomingNotify........................................................................................................ 65

3.2.11 incomingMessage.................................................................................................. 66

3.2.12 incomingInfo........................................................................................................... 66

3.2.13 callScreenSharingEnded........................................................................................ 67

3.2.14 incomingSubscribe.................................................................................................68

4 Use Examples 70
4.1 User Agent: Create Instance, Set Server and Account..........................................70
4.2 User Agent: Set Listeners (Callbacks)...................................................................70
4.3 User Agent Init: Connection to SBC Server and Login..........................................70
4.4 Make a Call........................................................................................................... 70
4.5 Send DTMF During Call........................................................................................70
4.6 Mute / Unmute During Call....................................................................................70
4.7 Accept Incoming Call.............................................................................................70
4.8 Reject Incoming Call.............................................................................................71
4.9 Terminate a Call....................................................................................................71
4.10 Use of Remote Streams Video..............................................................................71
4.11 Restore Call after Page Refresh............................................................................71
4.12 Set Custom Logger...............................................................................................72
4.13 Getting Statistics...................................................................................................72
4.14 Incoming Call with Replaces Header.....................................................................73
4.15 Incoming Call with Custom Headers.....................................................................74
5 Tutorial 76

API Reference Guide 6 Document, #, LTRT-14054


API Reference Guide Contents

This page is intentionally left blank.

Version 1.15 7 WebRTC


Notice
Information contained in this document is believed to be accurate and reliable at the time of
printing. However, due to ongoing product improvements and revisions, AudioCodes cannot
guarantee accuracy of printed material after the Date Published nor can it accept
responsibility for errors or omissions. Updates to this document can be downloaded from
https://www.audiocodes.com/library/technical-documents.
This document is subject to change without notice.
Date Published: July-04-2021

WEEE EU Directive
Pursuant to the WEEE EU Directive, electronic and electrical waste must not be disposed
of with unsorted waste. Please contact your local recycling authority for disposal of this
product.

Customer Support
Customer technical support and services are provided by AudioCodes or by an authorized
AudioCodes Service Partner. For more information on how to buy technical support for
AudioCodes products and for contact information, please visit our Web site
https://www.audiocodes.com/services-support/maintenance-and-support.

Stay in the Loop with AudioCodes

Abbreviations and Terminology


Each abbreviation, unless widely used, is spelled out in full when first used.

Version 1.15 9 WebRTC


WebRTC Web Browser Client

Document Revision Record

LTRT Description

14040 Initial document release for Version 1.0


14041 Updated to Version 1.1
14042 Added deinit and setDtmfOptions
14043 Update for Version 1.3: Added setOAuthToken and setEnableAddVideo
14044 Updates for Version 1.4 (added the following new functions):
 getBrowserName()
 getServerAddress()
 checkAvailableDevices()
 getStreamInfo()
 startSendingVideo()
 hasVideo()
 hasSendVideo()
 hasReceiveVideo()
 getVideoState()
 setRemoteHoldState()
14045 Updates for Version 1.5:
 Added optional
callbacks:
 callIncomingReinvite()
 transferorNotification()
 transfereeRefer()
 transfereeCreatedCall()
 Added function:
sendRefer()
14046 Updates for Versions 1.6 and 1.7:
 Added support
for Safari 12.0.0 and higher
 Added optional
callback: incomingNotify()
14047 Updates for Version 1.8:
 Added support
for incoming call with Replaces header (see incomingCall callback)
 Added support
for sending/receiving a SIP MESSAGE
 Added support
for attended call transfer.

API Reference Guide 10 Document, #, LTRT-14054


API Reference Guide Notices

LTRT Description

14048 Updates for Version 1.9:


 Updated to use
Chrome Unified SDP plan
 Removed SDP
editing and instead used transceiver API
 Obsolete
RTCPeerConnection addstream event replaced to track events
 Removed usage
of obsolete RTCPeerConnection.getLocalStreams() and getRemoteStreams()
As result of the modification method, phone.getWR().connection.getStreamInfo()
was replaced to phone.getWR().stream.getInfo()
Added new methods to use and instead removed
call.getRTCLocalStream() and call.getRTCRemoteStream()
 Modified
implementation of call video flags (hasVideo(), hasReceiveVideo(),
 hasSendVideo(), getVideoState()
 Value call.data[‘_video’ is no longer used
 For incoming call the flags set according initial INVITE SDP
 The flags updates
according answer SDP (hold SDP is ignored)
 Added
call.hasEnabledReceiveVideo() flag. Initially set according phone.enableAddVideo
flag. Set also for outgoing video call, or when used answer with phone.VIDEO or
phone.RECVONLY_VIDEO, or startSendingVideo(enableReceiveVideo=true)
 Added
call.hasEnabledSendVideo() flag. Set for outgoing video call, answer with
phone.VIDEO or then called startSendingVideo() method.
 Added support of
arbitrary audio and video constraints using methods:
 phone.setConstraints() and phone.setBrowsersConstraints().
 Marked as obsolete phone.setChromeAudioConstraints().
 Please use instead phone.setConstraints(‘chrome’, ‘audio’, {…})
 Modified
withVideo argument of call and answer.
 Instead of Boolean true/false, use phone.AUDIO, phone.VIDEO and
phone.RECVONLY_VIDEO.
 Modified internal
method: detectBrowser() - now phone.browser variable can be:
 One of ‘chrome’ (for Chrome and Chrome-based browsers, includes new
Microsoft Edge), ‘firefox’, ‘safari’, and ‘other’ (cannot detect browser).
 Improved detection of Chromium-based browsers for logging
 Removed special
support of Legacy Microsoft Edge. Now it is detected as ‘other’
browser in AudioCodes User Agent, AudioPlayer and AudioRecorder.
 Removed method
call.isHoldInProgress().
 Added method
call.stopSendingVideo()

Version 1.15 11 WebRTC


WebRTC Web Browser Client

LTRT Description

14049 Updates for Version 1.10:


 Removed the
Authentication Bearer header from INVITE OK
 Added new
optional argument to phone.setOAuthToken(token, useInInvite=true)
 Added
phone.setModes method to configure SDK modes
 Added
workaround to missed currently in Chrome RTP timeout detection (can be
configured via phone.setModes method)
 Added a new
argument 'hasSDP' for incomingCall callback ('true' when incoming SIP INVITE has
SDP body)
 Added an optional
argument pongDistribution, to setWebSocketKeepAlive. This argument is printed in
Keep Alive statistics. Not only the minimum and maximum values of pong delay,
but also the delay distribution.
 Added sound
configuration to utils.js audioPlayer by editing the configuration file (See
https://webrtcdemo.audiocodes.com/sdk/)
14050 Updates for Version 1.11:
 chrome_rtp_timeo
ut_fix
 Added setModes
setting: ice_timeout_fix
 Added setModes
setting: sbc_ha_pairs_mode
 Added method
sendInfo to class AudioCodesSession
 Added callback
incomingInfo
Updates for Version 1.12
14051  Added partial
support of IPhone iOS Safari
 Added setModes
ringing_header_mode (to add arbitrary SIP headers to SIP 180 response)
 Added support of
SBC REGISTER 3xx response (redirect to other SBC)
 Modified
argument for methods: startSendingVideo, stopSendingVideo, sendReInvite
14052 Updates for Version 1.13
 Added methods to switch current SBC: getNumberOfSBC and switchSBC
 Added screen sharing support: methods: startScreenSharing, stopScreenSharing
and callback callScreenSharingEnded
 Added argument extraOptions to methods call.answer() and phone.call()

API Reference Guide 12 Document, #, LTRT-14054


API Reference Guide Notices

LTRT Description

14053 Updates for Version 1.14


 Using outbound DTMF for Safari. SDK detects if Safari API supported DTMF
sender, for obsolete Safari versions DTMF via SIP INFO will be used.
Improved callback loginStateChanged() for ‘login’ set response argument to allow
checking REGISTER OK response.
 Modified screen-
sharing API to use for multiple calls.
 Added methods openScreenSharing(), closeScreenSharing(),
isScreenSharingSupported(),isScreenSharing() and
doesScreenSharingReplaceCamera()
 Modified startScreenSharing(), stopScreenSharing() and usage of callback
callScreenSharingEnded.
 Modified method setWebSocketKeepAlive()
 Added setNetworkPriority
14054 Updates for Version 1.15
 Added methods subscribe, notify and incomingSubscribe callback.
 Added ACD support. Files broadsoft_acd.js and pjxml.js.

Documentation Feedback
AudioCodes continually strives to produce high quality documentation. If you have any
comments (suggestions or errors) regarding this document, please fill out the
Documentation Feedback form on our Web site at
https://online.audiocodes.com/documentation-feedback.

Version 1.15 13 WebRTC


WebRTC Web Browser Client

1 Introduction
WebRTC technology enriches user experience by adding voice, video and data
communication to the Web browser, as well as to mobile applications. AudioCodes
WebRTC gateway provides seamless connectivity between WebRTC clients and existing
VoIP deployments.
A typical WebRTC solution comprises a WebRTC Gateway, which is an integrated
functionality on AudioCodes SBCs, and a client application running on a browser or a
mobile application. AudioCodes WebRTC client SDK is a JavaScript code that allows web
developers to integrate WebRTC functionality into the browser for placing calls from the
browser to the SBC.

Note: For a simple click-to-call button use case, a WebRTC widget is offered which can
be easily integrated into websites and blogs without any JavaScript knowhow. See the
WebRTC Widget Installation and Configuration Guide.

1.1 Purpose
This Reference Guide defines Application Programming Interface (API) use of the Web
Real-Time Communications (RTC) SDK.

1.2 Scope
The guide describes the API that must be implemented to use AudioCodes' Web RTC SDK
to build a Web phone client that will interact with AudioCodes' server to establish voice and
video calls. The guide may be used by web developers and application developers who
want to use the AudioCodes-provided SDK to build Web RTC clients.

1.3 Benefits
The following summarizes the benefits you'll gain from the API:
 Simple deployment - a single WebRTC gateway device for both signaling and media
 Strong security and interoperability capabilities resulting from integration with the SBC
 Client SDK for browsers
 OPUS powered IP phones for superb, transcoder-less voice quality

API Reference Guide 14 Document, #, LTRT-14054


API Reference Guide 2. API Classes

This page is intentionally left blank.

Version 1.15 15 WebRTC


WebRTC Web Browser Client

2 API Classes
Two usable objects are available:
 AudioCodesUA – Audio Codes User Agent (single tone) – see below
 AudioCodesSession – for call representation – see below

2.1 AudioCodesUA
AudioCodesUA is used to initialize the framework before starting to make and receive calls.
This class is mostly used to initialize the Web RTC engine and to register to the service.
Class AudioCodesUA{
constructor()
void setAccount (String userName, String displayName, String password, String
authName=userName);
void setServerConfig(List<InetSocketAddress> serverAddresses,
String serverDomain, List<IceConfig> iceServers=[]);
void setListeners (listeners);
void init(Boolean autologin=true);
void login();
void logout();
AudioCodesSession call(symbol videoOption, String call_to, extraHeaders=null,
extraOptions=null);
void setRegisterExtraHeaders (List<SipHeader> extraHeaders); extraHeaders);
void setUseSessionTimer(Boolean use);
void setRegisterExpires(int expires);
Boolean isInitialized();
String version();
void setUserAgent(String name);
void setConstraints(String browser, String type, Object constrains);
setBrowsersConstraints(Object object);
void setAcLogger(Function logger);
void setJsSipLogger(Function logger);
void setWebSocketKeepAlive(int pingInterval, Boolean pongTimeout=true, Boolean
timerThrottlingBestEffort=true, int pongReport=0, Boolean pongDist=false);
void setReconnectIntervals(int min, int max);
void deinit();
void setDtmfOptions(Boolean useWebRTC, int duration=null, int interToneGap=null)
void setOAuthToken(String token, Boolean useInInvite=true)
void setEnableAddVideo(Boolean enable)
String getBrowserName()
String getServerAddress()
Promise checkAvailableDevices()
Promise getWR().stream.getInfo(MediaStream stream)
Promise getWR().connection.getTransceiversInfo(RTCPeerConnection conn)
Promise getWR().connection.getStats(RTCPeerConnection conn, String array reportNames)
void setModes(Object modes)
int getNumberOfSBC()
void switchSBC()
Promise openScreenSharing()
void closeScreenSharing(stream)
Boolean isScreenSharingSupported()
void setNetworkPriority(String priority)
Subscriber subscribe(String target, String eventName,
String accept, SubscriberOption option)

API Reference Guide 16 Document, #, LTRT-14054


API Reference Guide 2. API Classes

Notifier notify(IncomingRequest subscribe,String contentType,


Notifier option)
}

Version 1.15 17 WebRTC


WebRTC Web Browser Client

2.1.1 Standard Methods

2.1.1.1 constructor

Creates the object instance.

2.1.1.2 init

Initializes the user agent and establishes a connection with the AudioCodes Mediant
server.

Parameter
 Autologin:true After connection, automatically call login()] (Optional). By default, 'true'.

Return Values
N/A

2.1.1.3 setServerConfig

Configures the AudioCodes Mediant server.

Parameters
 ServerAddresses:
 serverAddresses: inetSocket Address List of the AudioCodes Mediant servers
 serverAddresses [integer]: Two elements array list; where each array in the list
contains the inetSocket Address of the AudioCodes Mediant servers and priority
 serverDomain [string]: String of the domain name to which to register
 iceServers: List of the STUN and TURN servers
This optional parameter is by default set as an empty list [].
If it is used as an empty list during the call opening, an external STUN server is not
used. This mode is useful when the phone is used towards an SBC server.

Note: When the iceServers list is empty, after the call opens, the client still periodically
sends STUN requests to the port used for the RTP stream for checking that the RTC
channel is alive.

Return Values
N/A

API Reference Guide 18 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.1.1.4 setAccount

Defines the account details.

Parameters
 userName [string]: Authenticating user name
 displayName [string]: Displayed string name shown in the client interface
 password [string]: Authenticating user password
 authName [string]: Authorization user name (optional)

Return Values
N/A

2.1.1.5 login

Performs registration to the service.

Parameters
N/A

Return Values
N/A

2.1.1.6 logout

Performs de-registration from the service.

Parameters
N/A

Return Values
N/A

2.1.1.7 setListeners

Defines the listeners object.

Parameter
 Listener [Object that holds the methods to be triggered; See Section 4.2, User Agent:
Set Listeners (Callbacks) for an example]

Return Values
N/A

Version 1.15 19 WebRTC


WebRTC Web Browser Client

2.1.1.8 call

Initiates an outgoing call.

Parameters
 videoOption [symbol] phone.VIDEO: Defines if the call must be initiated with video, or
phone.AUDIO
 call_to [string]: Defines a string of the destination address/number

Return Values
A call session object is defined here.

Note: This call is also provided with another parameter (see Section 2.1.2).

API Reference Guide 20 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.1.2 Advanced Methods


The advanced methods are optional. They provide the API, which is based on SIP
(Session Initiation Protocol), with an extra level of flexibility. Developers familiar with SIP
can utilize the advanced methods.

2.1.2.1 setRegisterExtraHeaders

Allows adding additional headers to the registration request.

Note: The headers must be SIP headers that conform to RFC 3261.

Parameter
 ExtraHeaders [List of headers]

Return Values
N/A

2.1.2.2 call

Initiates an outgoing call.

Parameters
 videoOption [symbol] phone.VIDEO if the call must be initiated with Video, or
phone.AUDIO for audio call.
 call_to [string]: Destination address/number
 extraHeaders (Optional). An array of strings, each representing a SIP header, to be
added to the INVITE request.
 extraOptions (Optional). The object sets options to the internal method jssip.call.
 Can be used to set custom media streams for created calls.

Note: See also Use Examples under Section 4 for adding a SIP 'Replaces' header to
restore a call after a page reload.

Return Values
A call session object defined as shown under Section 2.2.

Version 1.15 21 WebRTC


WebRTC Web Browser Client

2.1.2.3 setUseSessionTimer

Allows enabling SIP session timers in the call session. If not used, the default value 'false'
is used.

Parameter
 enable [Boolean]: 'true' if yes; 'false' if no

Return Values
N/A

2.1.2.4 setRegisterExpires

Changes the default registration interval from the default value (600).

Parameter
 expires [integer] in seconds.

Return Values
N/A

2.1.2.5 isInitialized

Checks if the init() method was called.

Parameters
N/A

Return Values
Boolean

2.1.2.6 version

Retrieves a string with the API version.

Parameters
N/A

Return Values
String containing the API version.

API Reference Guide 22 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.1.2.7 setChromeAudioConstraints

This method is now obsolete. Use setConstraints or setBrowserConstraints instead.

Note: The method with the “echoCancellation” argument, performs exactly the same as
setConstraints(“chrome”, “audio”, {echoCancellation: true}).

It changes the echo cancellation and noise suppression flags, specifically for the Chrome
browser.

Parameters
 String with parameters, delimited by comma. The following can be used:
"autoGainControl,echoCancellation"
or "autoGainControl"
or “echoCancellation"
or “”

Return Values
N/A

2.1.2.8 setConstraints

Note: Google releases new builds of the Chrome browser generally every six weeks.
Each new release may change or ignore previously supported audio or video
constraints. The developer can check which parameters are used by opening the
phone prototype in one tab, and chrome://webrtc-internals in the other tab. Calls can
then be made to the other phone and check which audio constraints are used in
GetUserMediaRequest in the webrtc-internals page.

Parameters
 browser name [string] “chrome” or “firefox” or “safari” or “other”
 type [string] “audio” or “video”
 constraints [object] constraints in format described:
https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API/Constraints

This can be used for complex formatting including the following keywords:
 min
 max
 ideal
 exact
 advanced

Version 1.15 23 WebRTC


WebRTC Web Browser Client

A media constraint can be specified as mandatory (using the keyword: “exact”), and as an
optional (keyword: “ideal”) or without any keyword.
It is better to avoid mandatory constraints, since it cannot be confirmed whether the
constraint is supported in the user's browser. It depends on what operating system, driver
version and video and audio hardware is being used.
When using a mandatory format and the specified constraint is not supported, the call fails
with a "User Denied Media Access" error.
In the console log, it appears as "getusermediafailed" [error:OverconstrainedError ...]
To prevent this error from occurring, it is recommended to use the optional constraint
format.
This example causes the call to fail, if the Web camera you are using does not support the
“facingMode” constraint:
setConstraints(“chrome”, “video”, {facingMode: {exact: “user” }});

To prevent such errors, optional constraints format should be used:


setConstraints(“chrome”, “video”, { facingMode: { ideal:
“user” }});

Before using this format, check if the constraint is supported by your computer hardware,
and use ‘ideal’,’min’, ‘max’ constraints keywords instead of using ‘exact’.
let supported = navigator.mediaDevices.getSupportedConstraints();

// set audio constraints


let ac = {};

ac_log('Volume is supported: ', supported.volume ? true : false);


if (supported.volume){
ac.volume = 0.7;
}

ac_log('Echo cancellation is supported: ',


supported.echoCancellation ? true : false);
if (supported.echoCancellation){
ac.echoCancellation = true;
}

if (Object.keys(ac).length > 0){ // Is not empty ?


phone.setConstraints(phone.getBrowser(), 'audio', ac);
}

// set video constraints


let vc = {};

ac_log('webcam facing mode is supported: ', supported.facingMode ?


true : false);
if (supported.facingMode){
vc.facingMode = { ideal: 'user' };
}

API Reference Guide 24 Document, #, LTRT-14054


API Reference Guide 2. API Classes

ac_log('webcam aspect ratio is supported: ', supported.aspectRatio


? true : false);
if(supported.aspectRatio){
vc.aspectRatio = 1.0;
}

if (Object.keys(vc).length > 0){ // Is not empty ?


phone.setConstraints(phone.getBrowser(), 'video', vc);
}

To prevent the “overconstrained error” from occurring in the WebRTC getUserMedia


method,
check that the used constraint is supported and/or use the optional constraint format.
Refer to the WebRTC specification constraints description keywords: “ideal”, and
“advanced”.

Return Values
N/A

2.1.2.9 setBrowsersConstraints

Used to set constraints for all browsers.


Internally used setConstraints function with its limitations.

Note: In most situations, the exact camera or sound card each customer uses is
unknown. To prevent the occurrence of the “overconstrained error”, use the optional
constraint format.
For more information on WebRTC specification constraints descriptions for the “ideal”,
and “advanced” keywords, refer to https://developer.mozilla.org/en-
US/docs/Web/API/Media_Streams_API/Constraints.

Parameters
Constraints for set of browsers [object].
For example:
{
chrome: {
audio: { echoCancellation: true, noiseSuppression: true, audioGainControl: true },
video: { aspectRatio: 1.0 }
},
firefox: {
audio: { echoCancellation: true }
},
safari: {
audio: { echoCancellation: true }
},
ios_safari: {
audio: { echoCancellation: true }
},

Version 1.15 25 WebRTC


WebRTC Web Browser Client

The following browser names can be used: ‘chrome’, ‘firefox’, ‘safari’, ‘ios_safari, ‘other’.

Return Values
N/A

2.1.2.10 setUserAgent
Configures the User Agent string used to build the SIP header User-Agent.

Parameter
 User agent [string]

Return Values
N/A

2.1.2.11 setAcLogger
Configures the logger function that is used by AudioCodes' API for logging. By default, the
console log is used.

Parameter
 User-defined Logger function name.

Return Values
N/A

2.1.2.12 setJsSipLogger
Configures the logger function that is used by the JsSIP API for logging. By default,
console.log is used.

Note: This function does not support all JsSIP logging functionality. For SIP errors,
JsSIP uses other loggers that are not exposed and cannot be reassigned (see the
'debugerror' loggers in the JsSIP source code).

Parameter
 User-defined logger function name.

Return Values
N/A

API Reference Guide 26 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.1.2.13 setWebSocketKeepAlive
Used to send a CRLF Keep-alive message via WebSocket to the SBC. Based on RFC
7118, #6

Purpose
Enables fast detection of a server connection failure, and reconnection.
Refresh NAT connection.

Use
Used before SBC connection, before calling the "init" function.

Description
Sends a ping to the server and expects a ping response before the next ping is sent.
Detects intensive timer throttling (it can be applied if the page is hidden).
If timerThrottlingBestEffort is enabled (value != false or object interval > 0), increase the
ping interval to exit from intensive timer throttling mode.

Parameters
 pingInterval ping interval in seconds [Number]
 0: Do not send pings
 >0: Ping interval
 pongTimeout [Boolean]
 true (default) Close WebSocket after ping timeout
 false: Log warning and do not close WebSocket after ping timeout
 timerThrottlingBestEffort [Boolean or Object]
 true: (default)
For Chrome, increase the ping interval to exit from intensive timer throttling mode
(with timer resolution 60 seconds).
Check when the page is visible or there is an active call; in such cases, restore
the original value of the timer interval.
For Firefox and Safari, a warning is displayed and no action is taken.
 false: A warning is displayed if timer throttling is detected. No action is taken.
 Object with the format:
{ log: 0,
chrome: {
interval: 62,
visibility: true,
call: true,
log: 1
}
}
For normal usage, set the value for timerThrottlingBestEffort: true or false.
For debugging or fine tuning, use the object.

Version 1.15 27 WebRTC


WebRTC Web Browser Client

The object {log: 0, chrome: { interval: 62, visibility: true, call: true, log: 1 }}
is used internally if timerThrottlingBestEffort is set to true

The object { log: 0 }


is used internally if timerThrottlingBestEffort is set to false

Can be used with other values:


To check how Safari uses intense throttling, set
{ log: 1, chrome: { interval: 62, visibility: true, call: true} }

In this case, each big (> 10 seconds) ping timer deviation will be displayed.
In Safari 14.0.3, the deviation is random and less than 60 seconds, but in future
versions it may change.

When the used timerThrottlingBestEffort=true or false for a browser that is different to


Chrome, the log level is 0. This means that the detected timer throttling warning will be
displayed only once.

Another example: For debugging the display timer deviation, in milliseconds, for each
ping sent:
{ log: 3, chrome: { interval: 62, visibility: true, call: true}}

log: [integer] log level for all browsers.


0 changed ping interval, detected timer throttling displayed only once.
1 changed ping interval and each detected timer throttling.
2 all relative events (changed page visibility or call started/terminated)
3 each ping shows the timer deviation, in milliseconds
Levels 2 and 3 for debugging.
The parameter log can be set also for the browser setting if it overloaded the value.

Browser names and actions.


Can be seen that defined action only for Chrome.

interval: [integer] increased ping interval after timer throttling is detected.


To allow Chrome exit from intensive timer throttling mode, the interval must
Be more than 60 seconds

visibility: [Boolean] check page visibility:


when page is visible - use original ping interval value.
when page is hidden - use increased ping interval value provided that timer throttling
was previously detected.

call: [Boolean] Check if there is an active call.


If there is active call use original ping interval value.

log: [integer] optional.


Log value for the browser, if defined overload value for all browsers.

 pongReport Printing interval [Number]: The minimum and maximum values of pong
delay intervals (in milliseconds) every set number of times, are printed to the logs.
 0 : (default) No printing
 >0: Print report every number of pongs
 pongDist The ping delay distribution with time step 0.25 seconds was added to the
logs. [Boolean]
 true: Add to ping report interval distribution.
 false: (default) No print ping interval distribution.

API Reference Guide 28 Document, #, LTRT-14054


API Reference Guide 2. API Classes

Return Values
N/A

2.1.2.14 setReconnectIntervals
After a connection failure, the JsSIP stack automatically reestablishes a connection starting
from the minimum reconnection interval. If the reconnection is unsuccessful, the stack
increases the interval before the next reconnection, up to the maximum value. By default, 2
and 30 seconds are used for the minimum and maximum values.

Parameters
 Minimum reconnection interval [integer]
 Maximum reconnection interval [integer]

Return Values
N/A

2.1.2.15 deinit
Disconnects a WebSocket connection to the SBC server after gracefully unregistering and
terminating active sessions, if any.

isInitialized() returns 'false' after the method is used.

Parameters
N/A

Return Values
N/A

2.1.2.16 setDtmfOptions
Changes the DTMF options. If the method isn't called, DTMF is by default sent using
WebRTC API with default settings.

Parameters
 useWebRTC [Boolean]: Used to send DTMF WebRTC API [true], or use SIP INFO
[false]
 duration ms [integer] Optional. If the parameter is not set or is configured to 'null', 100
milliseconds is used by default.
 interToneGap ms [integer]: Optional. If the parameter is not set or is configured to
'null', 70 milliseconds is used by default for WebRTC and an interval of 500
milliseconds is used for separating SIP INFO messages.

Return Values
N/A

Version 1.15 29 WebRTC


WebRTC Web Browser Client

2.1.2.17 setOAuthToken
Sets the access token to OAuth2 authorization. This token is used while communicating
with AudioCodes SBC to authorize the user access. The Oauth token usage makes the
password usage redundant.

Parameters
 Token [string or null] .'null' can be used to clear the authorization token.
 useInInvite [Boolean] : Optional, by default 'true':
 If 'false', the "Authorization: Bearer" header token is added only to the SIP
REGISTER request. This is used if the SBC supports early versions of the
Authorization bearer specification.
 If 'true', the "Authorization: Bearer" header token is added to the SIP REGISTER
and INVITE requests. This is used if the SBC supports the latest version of the
Authorization bearer specification.
This is set by default.

Return Values
N/A

2.1.2.18 setEnableAddVideo
If the call was opened as an audio call, and the other side sent a re-INVITE with the video,
this enables the use of one-way incoming video. Two-way video cannot be added because
video devices are requested with the getUserMedia command at call opening.
It may not be desirable to suddenly add one-way incoming video in the middle of a call. By
default, this feature is disabled.

Parameters
 enabled [Boolean]

Return Values
N/A

2.1.2.19 getBrowserName
Returns browser name and version. This function can be used for logging purposes.

Parameters
N/A

Return Values
String including browser name and version.

API Reference Guide 30 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.1.2.20 getServerAddress
Returns the URL of the currently connected SBC server. This function can be used to
restore the connection after reloading of Web page.

Parameters
N/A

Return Values
null (no connected server), or URL string of currently connected server.

2.1.2.21 checkAvailableDevices
This method has two functions:
 Checks if the WebRTC API is supported in the used browser. If not, the Promise
object will be rejected with the following string: “WebRTC is not supported in the
browser”.
 Checks available devices (speaker, microphone and camera). If the speaker is not
connected, the speaker Promise object is rejected with the following string:
“Missing a speaker! Please connect one and reload”
If the microphone is not connected, the microphone is rejected with the following string:
“Missing a microphone! Please connect one and reload”

Parameters
N/A

Return Values
The Promise object is resolved with hasWebCamera Boolean value and is rejected with a
string describing the problem (see above).

2.1.2.22 getWR().stream.getInfo
Gets stream information for debugging/logging purposes.

Parameters
 stream [MediaStream] – local or remote call media stream
(see methods getRTCLocalStream and call.getRTCRemoteStream())

Return Values
The Promise object is resolved with a string value.

Version 1.15 31 WebRTC


WebRTC Web Browser Client

2.1.2.23 getWR().connection.getTransceiversInfo
Gets transceivers information for debugging/logging purposes.

Parameters
 connection [RTCPeerConnection] of current call.
(see method getRTCPeerConnection)

Return Values
The Promise object is resolved with a string value.
2.1.2.24 getWR().connection.getStats
Gets connection statistics information for debugging / logging purposes.

Parameters
 connection [RTCPeerConnection] of current call. (see method
getRTCPeerConnection)
 report names. [strings array] Report names, for example: ['outbound-rtp', 'inbound-
rtp']

Return Values
The Promise object is resolved with a string value.

2.1.2.25 sendMessage
Sends text messages using SIP MESSAGE.

Notes:
 Currently the Mediant SBC does not support off-line messaging.
 To message recipient, the phone should be on-line (registered to SBC).
 If the recipient received a message, then the SIP response code is 2xx.
 If the recipient is off-line, the response code is 404 “User Not Found”
 The programmer should check the SBC response code using the returned
Promise object. This will be resolved for 2xx SIP response codes, and failed for
others.

Parameters
 to [string]: Recipient URL (format: user or user@host)
 body [string]: Text message
 contentType [string]: Optional. “text/plain” is used by default

API Reference Guide 32 Document, #, LTRT-14054


API Reference Guide 2. API Classes

Return Values
The Promise object is resolved if the SBC response includes response code 2xx, and fails
for other response codes.

2.1.2.26 setModes
Configures the SDK internal modes or SDK patches parameters. Some patches used in
SDK can cause problems and create new unforeseen problems for customers. Other
problems can already be fixed in browsers, while some patches require numerical settings.
It is better to make patches configurable and configure them or turn them off, if they are not
needed by specific customers.
All SDK patches have corresponding flags (some with numbers) in SDK. Each flag has a
default value in the SDK.
The value can be changed via method phone.setModes().
To set values, it is recommended that you use the config.js configuration file, which can be
changed without rebuilding the SDK or the phone.
Usage example:
Phone configuration file config.js:

let DefaultPhoneConfig = {
...
modes: {
chrome_rtp_timeout_fix: 13
},
...
version: '2-May-2020'
}

Set SDK modes or patches before phone.init()

// change default SDK configuration to custom.


phone.setModes(phoneConfig.modes);

phone.init(true);

Without rebuilding the phone, switching on/off and configuring SDK modes can be
performed. Supported properties of the modes object:
 chrome_rtp_timeout_fix (Default: 13)
The existing workaround can be viewed in the current Chrome version bug Chromium
Issue 982793: iceconnectionstate does not go to failed if connection drops . For more
information, open the following link in the Chrome browser:
https://bugs.chromium.org/p/chromium/issues/detail?id=982793
By default, an RTP timeout of 20 seconds is used. It takes 7 seconds for Chrome to
detect an RTP disconnection and then another 13 seconds to check that the
disconnection state has not changed. If the internet connection is restored, it is
changed to ‘connected’ state.
chrome_rtp_timeout_fix: 13
By changing the configuration value, the customer can increase or decrease the
timeout, or completely disable the Chrome bug workaround by setting:
chrome_rtp_timeout_fix: undefined

Version 1.15 33 WebRTC


WebRTC Web Browser Client

 ice_timeout_fix Default value: 0


After setting a local description, the WebRTC starts ICE gathering, without a timeout in
some cases. For Chrome, it can take 41 seconds.
When AudioCodes’ SBC is used, the phone functions without additional IPs provided by
ICE gathering. ICE gathering cannot be disabled, but a local SDP can be sent without
waiting for ICE gathering, so the default 0 means not to wait for ICE gathering at all.
The value is set in milliseconds. In SDK versions preceding 1.11, a hardcoded value
of 2000 was used.
If set to an undefined value, the ICE gathering timeout will not be checked and
sometimes (depending on the configuration of the user’s computer’s internet adapters)
will add for a Chrome delay of 41 seconds for an outgoing call between the command
‘make call’ and sending a SIP INVITE, and for an incoming call between the command
‘answer’ and the call opening.
 sbc_ha_pairs_mode Default value: undefined
If a customer uses multiple HA pairs, the value should be set to some integer value. In
testing, 15 (seconds) was used. After an SBC disconnection, JsSIP is reconnected to
a different URL (when multiple SBC URLs are used).
When High Availability SBC pairs are used, best to attempt to reconnect to the same
URL as was connected. If there is an undefined value, set a numeric (integer) value
instead. After a disconnection, JsSIP attempts to reconnect to the same URL during
the time (e.g., 15 seconds).
If the connection cannot be restored, then the default JsSIP algorithm (reconnect to
other URLs) will be used. The value should be undefined if a single URL is used, or if
multiple URLs of the SBC in simple (not HA pairs) configuration is used.

 ringing_header_mode Default value: undefined


Add additional SIP header(s) to ringing response (SIP response code 180)
For example, add Allow-Events SIP header:
ringing_header_mode: 'Allow-Events: talk,hold,conference'

Multiple SIP headers can be added, for example


ringing_header_mode: ['Allow-Events: talk,hold,conference',
'X-Greeting: Have a nice day !']

Parameter
 modes object

Return Values
N/A

API Reference Guide 34 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.1.2.27 getNumberOfSBC
Returns the number of SBC Server Addresses (set by setServerConfig serverAddresses).

Parameters
 N/A

Return Values
The number of SBC servers set in server configuration [integer].

2.1.2.28 switchSBC
Disconnects from the current SBC and switches to the other SBC.

Notes:
 You should have more than one SBC to use the method.
 Before switching SBC please check that you have no open calls on the
current SBC.

Parameters
N/A

Return Values
N/A

Version 1.15 35 WebRTC


WebRTC Web Browser Client

2.1.2.29 openScreenSharing
Returns the Promise object resolved with a screen sharing video stream.

Parameters
 N/A

Return Values
The Promise object is resolved with a video stream value and is rejected with a string
describing the problem (screen sharing is not supported or disabled by user).

API Reference Guide 36 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.1.2.30 closeScreenSharing
Returns the number of SBC Server Addresses (set by setServerConfig serverAddresses).

Parameters
 Video stream object created previously by method openScreenSharing()

Return Values
N/A

2.1.2.31 isScreenSharingSupported
Checks if screen sharing API is supported in the current browser.

Parameter
N/A

Return Values
Boolean

2.1.2.32 setNetworkPriority
Changes the sending RTP packets IP DSCP field.
The method works only for Chrome browser and ignored by others.

Parameters
 priority [string or undefined]
Allowed value: undefined,  'high',  'medium',  'low',  'very-low'
If method don't used or set undefined value – DSCP don't changed.

2.1.2.33 subscribe
Uses JsSIP subscribe extension to create SIP SUBSCRIBE dialog.

Parameters
 target [string]: send SUBSCRIBE request to the target.
 eventName [string]: event name
 accept [string]: header value
 subscriberOption [object]: All properties are optional.
 expires [number]: SUBSCRIBE expires. Default is 900
 contentType [string]: Content-Type header value. Used for SUBSCRIBE with
body
 allowEvents [string]: Allow-Events header value.

Version 1.15 37 WebRTC


WebRTC Web Browser Client

 params [RequestParams] If set please define: to_uri, to_display_name,
  from_uri, from_display_name
 extraHeaders [array of strings]: adds extra SIP headers to SUBSCRIBE.

Return Values
 Subscriber class instance.

2.1.2.34 notify
Use JsSIP notify extension to create SIP NOTIFY dialog.

Parameters
 subscribe [IncomingRequest]: subscribe incoming request.
 contentType [string]: Content-Type header value. Used for NOTIFY
 option [NotifierOption] All properties are optional.
 pending [boolean]: Create notifier in ‘pending’ state
 Default is false – notifier created in ‘active’ state.
 allowEvents [string]: Allow-Events header value.
 extraHeaders [array of strings]: adds extra SIP headers to NOTIFY.

Return Values
 Notifier class instance.

API Reference Guide 38 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.2 AudioCodesSession
Represents a call session that is used in the following scenarios:
 When initiating a call via the AudioCodesUA
 When receiving a callback of an incoming call

Syntax
class AudioCodesSession {
void answer (symbol videoOption, extraHeaders=null, extraOptions=null);
void reject ()
void redirect(String callTo)
void terminate ()
void muteAudio(Boolean mute)
void muteVideo(Boolean mute)
Boolean isAudioMuted()
Boolean isVideoMuted()
void sendDTMF(char dtmf)
Boolean isOutgoing()
Map<String, Object>data;
int duration()
Boolean isLocalHold()
Boolean isRemoteHold()
Boolean isReadyToReOffer()
Promise hold(Boolean holdCall)
string getReplacesHeader()
Promise startSendingVideo(options = {})
Promise stopSendingVideo(options = {})
Boolean hasVideo()
Boolean hasSendVideo()
Boolean hasReceiveVideo()
string getVideoState()
Boolean hasEnabledSendVideo()
Boolean hasEnabledReceiveVideo()
string getEnabledVideoState()
void setRemoteHoldState()
RTCPeerConnection getRTCPeerConnection()
MediaStream getRTCLocalStream()
MediaStream getRTCRemoteStream()
Promise sendReInvite(options = {})
Boolean wasAccepted()
void sendInfo(body, contentType, extraHeaders=null)
Promise startScreenSharing(stream)
void stopScreenSharing()
Boolean isScreenSharing()
Boolean doesScreenSharingReplaceCamera()
}

Version 1.15 39 WebRTC


WebRTC Web Browser Client

2.2.1 Standard Methods

2.2.1.1 answer

Initiates the object and establishes the call.

Parameter
videoOption [symbol] one of phone.VIDEO, phone.RECVONLY_VIDEO or phone.AUDIO

Return Values
N/A

Note: This call is also provided with another parameter (see Section 2.2.2.1)

2.2.1.2 reject

Rejects a call.

Parameters
N/A

Return Values
N/A

Note: This call is also provided with another parameter (see Section 2.2.2.2)

API Reference Guide 40 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.2.1.3 redirect

Redirects the call and asks the caller to call the destination.

Parameter
 Call_to [string of destination address/number]: Used for SIP response code 302 with
Contact header.

Return Values
N/A

Note: This call is also provided with another parameter (see Section 2.2.2.3)

2.2.1.4 terminate

Terminates an active call.

Parameters
N/A

Return Values
N/A

Version 1.15 41 WebRTC


WebRTC Web Browser Client

2.2.1.5 muteAudio

Defines the status of the audio mute (on/off).

Parameter
 Mute [Boolean]: 'true' to mute audio; 'false' to unmute audio

Return Values
N/A

2.2.1.6 muteVideo

Defines the status of the video mute (on/off).

Parameter
 mute [Boolean]: 'true' to mute video; 'false' to unmute video

Return Values
N/A

2.2.1.7 isAudioMute

Checks the audio mute status.

Parameters
N/A

Return Values
[Boolean]: 'true' if audio is muted, 'false' if audio is unmuted.

2.2.1.8 isVideoMute

Checks video mute status.

Parameters
N/A

Return Values
[Boolean]: 'true' if video is muted, 'false' if video is unmuted

API Reference Guide 42 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.2.1.9 sendDTMF

Sends a DTMF character.

Parameter
 dtmf [One DTMF character]

Return Values
N/A

2.2.1.10 isOutgoing
Checks if a call is outgoing.

Parameters
N/A

Return Values
[Boolean]: 'true' if a call is outgoing, 'false' if a call is incoming

2.2.1.11 data: map<String, Object>


Data are object variables, represented by a key / value list into which API developers can
enter a string key and an object value for later use in the program flow. Example: String
key 'label' and an object reference to the GUI object. This provides API developers with
flexibility to use string keys and values for implementation. This data assists API
developers to distinguish between implementation scenarios.

Note: Variables with a name starting with underscore ‘_’ are reserved for internal API
usage. Developers should not use these variables.

Predefined Parameters
data['_user'] Remote user name set according to the SIP header 'To'
(outgoing call), or 'From' (incoming call).
data['_host'] Remote host set according to the SIP header 'To' (outgoing
call), or 'From' (incoming call).
data['_display_name'] Remote user optional display name; set according to SIP
header 'To/From' (the same as _user).
data['_create_time'] Timestamp(javascript Date()) of the call created. For call
logging, the time and call duration (duration between call
confirmation and call termination) are used.

Version 1.15 43 WebRTC


WebRTC Web Browser Client

2.2.1.12 duration
Defines the call duration (in seconds).
If this method is used before the call has been accepted (i.e., sends or receives SIP OK
response), it returns "0".
If this method is used for an open call, it returns intervals after the call has been accepted
until the current time.
After call termination, it returns call duration from the time the call has been accepted until
the time the call terminated.

Parameters
N/A

Return Values
[int]: call duration in seconds

2.2.1.13 wasAccepted
Defines whether the call has been accepted (sends or receives a SIP OK response).
This method can be used after call termination, to check if the call was established or
failed.

Parameters
N/A

Return Values
[Boolean]: 'true' when the call was accepted

2.2.1.14 isLocalHold
Defines whether the client initiates the hold state. This indicates that the client can release
the hold.

Parameters
N/A

Return Values
[Boolean]: 'true' if the call is in a local hold, 'false' if it isn't in a local hold.

API Reference Guide 44 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.2.1.15 isRemoteHold
Defines whether the remote side initiated the hold. This indicates that the client cannot
release the hold.

Parameters
N/A

Return Values
[Boolean]: 'true' if the call is in a remote hold. 'false' if it isn't in a remote hold.

2.2.1.16 IsReadyToReOffer
Implements a hold using SIP re-INVITE. It then checks, before using the hold, if the call is
ready to re-offer (i.e., ready to send the re-INVITE).

Parameters
N/A

Return Values
[Boolean] 'true' if call is ready to re-offer, 'false' if it isn't ready to re-offer.

2.2.1.17 hold
Sets the call to on-hold (or to un-hold).

Parameter
 Hold [Boolean]: Sets the call to hold.

Return Values
Promise to wait until the end of the operation.

Version 1.15 45 WebRTC


WebRTC Web Browser Client

2.2.2 Advanced Methods

2.2.2.1 answer

Initiates the object and establishes the call.

Parameters
 videoOption [symbol]:
 phone.VIDEO - This is used if the call uses two-way video
 phone.RECVONLY_VIDEO - Does not send video, but receives video
 phone.AUDIO - This is used for audio calls.
 extraHeaders (Optional): An array of strings, each representing a SIP header to add to
the request.
 extraOptions (Optional): The object set options to internal method jssip answer.

Return Values
N/A

2.2.2.2 reject

Rejects a call.

Parameters
 Status code (Optional): Integer representing the reject reason (4xx or 6xx codes, 486
busy (default))
 extraHeaders (Optional): An array of strings, each representing a SIP header to be
added to the request.

Return Values
N/A

2.2.2.3 redirect

Redirects the call; asks the caller to call the destination.

Parameters
 Call_to [string of the destination address/number]: Used for SIP response code 302
with Contact header.
 Status code [integer] (Optional): Integer representing the reject reason (3xx codes,
302 moved temporarily (default))
 extraHeaders [string array] (Optional): An array of strings, each representing a SIP
header to add to the request.

API Reference Guide 46 Document, #, LTRT-14054


API Reference Guide 2. API Classes

Return Values
N/A

2.2.2.4 getReplacesHeader

Retrieves the SIP 'Replaces' header that can be used to restore the last call after page
reloading. See the example in Section 4.11.

Parameters
N/A

Return Values
The string replaces the header value according RFC 3891, or 'null' if the call is not
established.
The string may be used to re-establish a failed call session on the client side (if a session
still exists on the SBC, for example, in the case of a page refresh).
See the Use Examples under Section 4 for more details.

2.2.2.5 getRTCPeerConnection

Retrieves the session internal RTCPeerConnection. For example, the object can be used
to collect call statistics.

Note: If a call is terminated, peerConnection is closed and statistics are not available
(closed by JsSip).

For more information on Peer Connection and GetStats, refer to


https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection and
https://www.callstats.io/2015/07/06/basics-webrtc-getstats-api/
See also the Use Examples under Section 4 for more details.

Parameters
N/A

Return Values
RTCPeerConnection object.

2.2.2.6 getRTCLocalStream

Retrieves the session internal media local stream.


For example, the object can be used to check audio and video tracks.

Parameters
N/A

Version 1.15 47 WebRTC


WebRTC Web Browser Client

Return Values
Local media stream

2.2.2.7 getRTCRemoteStream

Retrieves the session internal media remote stream.


For example, the object can be used to check audio and video tracks.

Note: Can be null, during call opening.

Parameters
N/A

Return Values
Remote media stream.

2.2.2.8 startSendingVideo

For audio calls, this methodstarts sending video stream to the other side.
Set internal call flag setEnabledSendVideo()

Parameters
 Object options. Default value is {}
 options.enableReceiveVideo [Boolean] by default is 'true'.
The argument sets the internal call flag hasEnabledReceiveVideo().
 options.extraHeaders [Array of String] by default undefined.
Adds extra SIP headers to re-INVITE.

Return Values
Promise object that is resolved if successfully started, and rejected otherwise.

API Reference Guide 48 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.2.2.9 stopSendingVideo

Stops sending video streams to the other side, for video calls.
Clears the setEnabledSendVideo() internal call flag.

Parameters
 Object options. Default value is {}
options.extraHeaders [Array of String] by default undefined.
Adds extra SIP headers to re-INVITE.

Return Values
The Promise object that is resolved if it successfully stops sending video streams.
Otherwise, it is rejected.

2.2.2.10 hasVideo, hasSendVideo, hasReceiveVideo


Checks call video status:
 hasVideo: Returns true if two-way video is connected for the session.
 hasSendVideo: Returns true if the outgoing video stream is connected for the session.
 hasReceiveVideo: Returns true if the incoming video stream is connected for the
session.
When a call is placed on hold, this method reflects the last status before the hold action.
For example, two-way video is enabled and then a call is placed on hold (no video and no
audio is active at this time); then the “hasVideo” value is returned.
This status is used for restoring call functionality and shows/hides GUI call video controls.

Parameters
N/A

Return Values
Boolean

2.2.2.11 getVideoStatus

Parameters
N/A

Return Value
[string] Representation of the call video status.
(one of ‘sendrecv’, ‘sendonly’, ‘recvonly’ or ‘inactive’)

Version 1.15 49 WebRTC


WebRTC Web Browser Client

Note: If a call was placed on hold, the video status will be the same as it was before it
was put on hold.

2.2.2.12 hasEnabledSendVideo, hasEnabledReceiveVideo


Checks if calls were enabled to send or receive video:
 hasEnabledSendVideo: Returns 'true' when a call was enabled to send video.
This is set when (phone.VIDEO), answer(phone.VIDEO) or startSendingVideo() are used.
This is 'false', when call(phone.AUDIO), call(phone.RECVONLY_VIDEO) or after
stopSendingVideo() are used.
If 'true', the current call tries to send a video. (The other side phone may not accept it.)
 hasEnabledReceiveVideo: Returns 'true' if the call is enabled to receive video.
This is initially set according to the phone.enableAddVideo flag.
This is also set according to the videoOption argument of call(), answer(),
startSendingVideo().

If this is 'false', the current call does not receive video, even if the other side starts sending
to it.

Return Values
Boolean

2.2.2.13 getEnabledVideoStatus

Parameters
N/A

Return Value
[string] representation of the call enabled video status
(one of ‘sendrecv’, ‘sendonly’, ‘recvonly’ or ‘inactive’)

2.2.2.14 setRemoteHoldState
Used to restore the call state after Web page reloading. Sets internal JsSIP Session state
corresponding to the call remote hold state.

Parameters
N/A

Return Values
N/A

API Reference Guide 50 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.2.2.15 sendRefer
Used to start the blind call transfer process. The developer should set the call on-hold
before using the sendRefer function. The transfer progress is checked by callback
“transferorNotification” (it must be set when sendRefer is used).

Parameters
 transferTo [string]: Call transfer destination
 probeCall [A call session object]: Optional. This parameter is used for attended
transfer. By default, null.

Return Values
N/A

2.2.2.16 sendReInvite
Sends the re-INVITE SIP message to the SBC server.

Parameters
 Object options. Default value is {}
 options.showStreams [Boolean] by default is 'false'.
Call callShowStreams callback after re INVITE transaction is completed.
Used to assign stream value to the srcObject HTML video element.

 options.extraHeaders [Array of String] by default is undefined.


Adds extra SIP headers to re-INVITE.

Return Values
Promise. Resolved if re-INVITE SIP transaction is complete.
Rejected if re-INVITE transaction failed.

2.2.2.17 sendInfo
Sends the INFO message to the SBC server.

Parameters
 body [string]: Text message
 contentType [string] Body content type.
extraHeaders [array of strings]: Optional. ‘null’ is used by default.

Return Values
N/A

Version 1.15 51 WebRTC


WebRTC Web Browser Client

2.2.2.18 startScreenSharing
For audio or video calls, this method starts sending screen sharing video track to the other
side.
For audio call will be added screen sharing video track.
For video call web camera video track will be replaced for screen sharing video track.
Set internal call flag setEnabledSendVideo()

Parameters
Screen sharing video stream opened by openScreenSharing()

Return Values
Promise object that is resolved if successfully started, and rejected otherwise.

2.2.2.19 stopScreenSharing
Stop sending screen sharing video track.
For video call will be restored previously sent web camera video track.

Parameters
N/A

Return Values
N/A

2.2.2.20 isScreenSharing
Checks if the call is currently sending a screen-sharing video stream.

Parameters
N/A

Return Values
Boolean

2.2.2.21 doesScreenSharingReplaceCamera
Checks if the call is sending a screen-sharing video stream and if it replaced the stream
previously sent from the camera. The method used to restore the call after page reloading.

Parameters
N/A

Return Values
Boolean

API Reference Guide 52 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.3 Subscriber
It is AudioCodes JsSIP extension that implements RFC 6665. The class instance is created
by the phone.subscribe() method.
Please see the API usage examples in the SDK:
 single call phone prototype (file phone.js)
 phone prototype with ACD (file broadsoft_acd.js)

Syntax

class Subscriber {
int state
String id
void subscribe(String body = null)
void terminate(String body = null)
void on(String event, Function callback)
void removeAllListeners(String event)
}

2.3.1 get state


Gets the subscriber dialog state.

Return Values
number
Possible values are:
 subscriber.C.INIT
 subscriber.C.STATE_NOTIFY_WAIT
 subscriber.C.STATE_PENDING
 subscriber.C.STATE_ACTIVE
 subscriber.C.STATE_TERMINATED

2.3.2 get id
Gets the unique subscriber dialog id.

Return Values
String

2.3.3 subscribe
Sends the SIP SUBSCRIBE request to the server.

Version 1.15 53 WebRTC


WebRTC Web Browser Client

Parameter
 body [String or null value]
 The value will be send as SUBSCRIBE request body.

Return Values
N/A

2.3.4 terminate
Sends the SIP un-SUBSCRIBE (subscribe with header Expires: 0) request to server.

Parameter
 body [String or null value]
The value will be sent as SUBSCRIBE request body.

Return Values
N/A

2.3.5 on
The Subscriber class extends the EventEmitter class that provide the on() method.
This is used to set the callback function to subscriber events.

Parameter
 eventName [String]
 ‘dialogCreated’ fired when the subscriber receives the OK response to the initial
SUBSCRIBE message. After the event, enqueued subsequent SUBSCRIBE
requests will can be sent.
Callback function arguments: N/A

 ‘pending’ fired when the subscriber state has changed to ‘pending’ state.
(received 1st NOTIFY with header Subscription-State: pending)
Callback function arguments: N/A

 ‘active’ fired when the subscriber state has changed to ‘active’ state.
(received 1st NOTIFY with header Subscription-State: active)
Callback function arguments: N/A

 ‘notify’ fired when the NOTIFY request has been received with no empty body.
Callback function arguments:
 isFinal [Boolean]. Is received NOTIFY with Subscription-State: terminated
 notify [IncomingRequest]. Received NOTIFY request.
 body [String] NOTIFY request body
 contentType [String]. Value of Content-Type header.

API Reference Guide 54 Document, #, LTRT-14054


API Reference Guide 2. API Classes

 ‘terminated’ fired when the subscriber has terminated.


Callback function argument:
 terminationCode [Number].
Possible values are:
 subscriber.C.SUBSCRIBE_RESPONSE_TIMEOUT
 subscriber.C.SUBSCRIBE_TRANSPORT_ERROR
 subscriber.C.SUBSCRIBE_NON_OK_RESPONSE
 subscriber.C.SUBSCRIBE_BAD_OK_RESPONSE
 subscriber.C.SUBSCRIBE_FAILED_AUTHENTICATION
 subscriber.C.UNSUBSCRIBE_TIMEOUT
 subscriber.C.RECEIVE_FINAL_NOTIFY
 subscriber.C.RECEIVE_BAD_NOTIFY

 reason [String or undefined] termination reason.


Defined when subscription termination reason is incoming final.
NOTIFY and header Subscription-State contains reason parameter.
 retryAfter [Number or undefined]
Defined when subscription termination reason is incoming final.
NOTIFY and header Subscription-State contains retryAfter
parameter.
 callback [Function]
Function with corresponding to event name arguments

Return Values
N/A

2.3.6 removeAllListeners
The Subscriber class extends the EventEmitter class that provides the
removeAllListeners() method.
Remove event listener function set by on() method.

Parameter
 eventName [String] Defines the event name.

Return Values
N/A

Version 1.15 55 WebRTC


WebRTC Web Browser Client

2.4 Notifier
It is AudioCodes JsSIP extension that implements RFC 6665. The class instance is created
by the phone.notify() method. See the API usage example in the SDK single call phone
prototype (file phone.js).

Syntax

class Notifier {
int state
String id
void start()
void setActiveState()
void notify(String body = null)
void terminate(String body = null, String reason = null,
int retryAfter = null)
void on(String event, Function callback)
void removeAllListeners(String event)
}

2.4.1 get state


Gets the notifier dialog state.

Return Values
number
Possible values are:
notifer.C.STATE_PENDING
notifier.C.STATE_ACTIVE
notifier.STATE_TERMINATED

2.4.2 get id
Gets the unique notifier dialog id.

Return Values
String

2.4.3 start
Lets the call after creating the Notifier instance and setting the event handlers.
Starts processing the initial SUBSCRIBE.

API Reference Guide 56 Document, #, LTRT-14054


API Reference Guide 2. API Classes

Parameters
N/A

Return Values
N/A

2.4.4 setActiveState
Switches notifier state from ‘pending’ to ‘active’ state.

Parameter
N/A

Return Values
N/A

2.4.5 notify
Sends the SIP NOTIFY request to the subscriber.
Used after receiving SUBSCRIBE or the system state has changed.

Parameter
 body [String or null value]
 The value will be sent as NOTIFY request body.

Return Values
N/A

2.4.6 terminate
Sends the final SIP NOTIFY request to the subscriber. This is used after receiving an un-
SUBSCRIBE, subscription time has expired or the
notifier wants to terminate the subscription.

Parameter
 body [String or null value]
The value will be sent as final NOTIFY request body.

Return Values
N/A

Version 1.15 57 WebRTC


WebRTC Web Browser Client

2.4.7 on
The Notifier class extends the EventEmitter class whicj provides the on() method.
This is used to set the callback function to notifier events.

Parameter
 eventName [String]
 ‘subscribe’ fired when received subscribe message (includes initial subscribe)
Callback function arguments:
 is_unsubscribe [Boolean] if received un-subscribe (with expires: 0)
 request [IncomingRequest] received subscribe
 body [String] optional subscribe body
 contentType [String] optional body content types
 ‘terminated’ fired when notifier is terminated.
Callback function argument:
 terminationCode [Number].
Possible values are:
 notifier.C.NOTIFY_RESPONSE_TIMEOUT
 notifier.C.NOTIFY_TRANSPORT_ERROR
 notifier.C.NOTIFY_NON_OK_RESPONSE
 notifier.C.NOTIFY_FAILED_AUTHENTICATION
 notifier.C.SEND_FINAL_NOTIFY
 notifier.C.RECEIVE_UNSUBSCRIBE
 notifier.C.SUBSCRIPTION_EXPIRED
 callback [Function]: function that will be called when the event fired.

Return Values
N/A

2.4.8 removeAllListeners
The Notifier class extends the EventEmitter class which provides the removeAllListeners()
method.
This removes the event listener function set by the on() method.

Parameter
 eventName [String] The event name.

Return Values
N/A

API Reference Guide 58 Document, #, LTRT-14054


API Reference Guide 2. API Classes

2.5 BoadsoftAcdAgent
The Automatic Call Distributor (ACD) is a device or system that distributes incoming calls
to a specific group of terminals that agents use.
Genesys server uses an ACD system built on the basis of the Broadsoft ACD specification.
To use the API, please add the following to the project files:
 broadsoft_acd.js (classes to work with ACD SUBSCRIBE/NOTIFY)
 pjxml.js (open source tiny XML parser)
Please take the files from the SDK phone prototype with ACD. The phone prototype with
ACD demonstrates the use of the API.

Syntax

class BroadsoftAcdAgent {
constructor()
void setListeners(Function stateChanged, Function errorListener)
void setLog(Function logger)
void setAccount(String acdUser, String acdPassword, int expires)
void setLoginState(String state, int substate)
void start()
void stop()
void logon()
void logoff()
void setState(String state, int substate)
}

2.5.1 constructor
Creates the object instance.

2.5.2 setListeners
Defines the listeners.

Parameter
 state listener [Function state(String state, int or undefined code]
 error listener [Function error(String message, Boolean isSubscriptionTerminated)

Return Values
N/A

2.5.3 setLog
Configures the logger function that is used by AudioCodes' API for logging. By default, the
console log is used.

Version 1.15 59 WebRTC


WebRTC Web Browser Client

Parameter
 User-defined Logger function name.

Return Values
N/A

2.5.4 setAccount
Defines the account details.

Parameters
 acdUser [string]: acd user name. Used as hoteling guest address.
 password [string]: authenticating user password
 expires [int]: set subscription expires (seconds)

Return Values
N/A

2.5.5 setLoginState
Sets the state that will be set during login. It should be used before the call logon() method.

Parameters
 state [string]: set acd agent state. Can be used values:
'ready', 'notReady', 'workingAfterCall'
 substateCode [int or undefined]: code for ‘notReady’ state. Positive number

Return Values
N/A

2.5.6 start
Performs subscription to ACD service.

Parameters
N/A

Return Values
N/A

2.5.7 stop
Performs un-subscription to the ACD service.

API Reference Guide 60 Document, #, LTRT-14054


API Reference Guide 2. API Classes

Parameters
N/A

Return Values
N/A

2.5.8 logon
Performs the logon on the ACD account.

Parameters
N/A

Return Values
N/A

2.5.9 logoff
Performs logoff on the ACD account.

Parameters
N/A

Return Values
N/A

2.5.10 setState

Sets the ACD state.

Parameters
 state [string]: set ACD agent state.
Values that can be used: 'ready', 'notReady', 'workingAfterCall'
 substateCode [int or undefined]: code for ‘notReady’ state.
 Positive number: 0, 1, 2, …

Return Values
N/A

Version 1.15 61 WebRTC


WebRTC Web Browser Client

3 API Callbacks / Listeners Interfaces


This API provides the capability to register to listen to different types of events. This section
lists the interfaces that must be implemented to receive such events.

3.1 Standard Callbacks


The following are standard callbacks.

3.1.1 Login State Changed Event


Triggered when the login state is changed.

Syntax
void loginStateChanged(Boolean isLogin, string cause);

Parameter
 IsLogin is 'true' if logged in, and 'false' if not logged in.
The cause is one of these strings:
 "connected"
 "disconnected"
 "login failed"
 "login"
 "logout"

3.1.2 Incoming Call Event


Triggered when receiving an incoming call.

Syntax
void incomingCall(AudioCodesSession call);

Parameter
 AudioCodesSession: The call session object

3.1.3 Call Confirmed


Triggered when the call is established.

Syntax
void callConfirmed(AudioCodesSession call);

Parameter
 AudioCodesSession: The call session object

API Reference Guide 62 Document, #, LTRT-14054


API Reference Guide 2. API Classes

3.1.4 Call Terminated


Triggered when a call is terminated or fails.

Syntax
void callTerminated(AudioCodesSession call, message, cause, redirectTo);

Parameters
 AudioCodesSession: The call session object
 Message: Reason of termination (optional)
 case [string]
 redirectTo [string]: (Optional) Destination of redirection, set when the 'case' parameter
is 'Redirected'.

3.1.5 Outgoing Call Progress


Triggered when a SIP 'trying' response or a SIP 'ringing' response is received.

Syntax
void outgoigCallProgress (AudioCodesSession call);

Parameter
 AudioCodesSession: The call session object

3.1.6 Call Show Streams


Triggered when local and remote audio and video streams are ready to be shown in view
panels.

Syntax
void callShowStreams(AudioCodesSession call, Stream localStream, Stream remoteStream);

Note: Only relevant for the browser API.

Parameters
 AudioCodesSession: The call session object.
 Localstream: The stream from the local camera and microphone.
 remoteStream: The stream from the remote camera and microphone.

Version 1.15 63 WebRTC


WebRTC Web Browser Client

3.2 Advanced Callbacks


The advanced callbacks are optional. They provide an extra level of flexibility to the API,
which is based on SIP. Developers who are familiar with SIP can utilize the advanced
callbacks.

3.2.1 Incoming call event


Triggered when receiving an incoming call.

Syntax
void incomingCall(AudioCodesSession call, SipRequest invite, AudioCodesSession replacedCall,
Boolean hasSDP);

Parameters
 AudioCodesSession [The call session object]
 SipRequest [The SIP request object]
 AudioCodesSession [The replaced call session object or null]
The replacedCall argument is not null, if the received INVITE includes a Replace header.
In this case, the programmer in the callback should terminate replacedCall,
automatically answer the incoming call, and visually (in GUI panel or window) make it
the replacement for the terminated call.
 hasSDP [Boolean]
Enabled for the phone developer for a special case – incoming INVITE without SDP.
(If it isn’t known whether the other side supports video calls, an answer can be made
with or without video).

3.2.2 Call Confirmed


Triggered when the call is established.

Syntax
void callConfirmed(AudioCodesSession call, SipMessage message, String cause);

Parameters
 AudioCodesSession: The call session object
 SipMessage: The OK SIP message of an outgoing call, or 'null' for an incoming call
The cause may be one of the following strings:
 "received ack"
 "sent ack"

API Reference Guide 64 Document, #, LTRT-14054


API Reference Guide 2. API Classes

3.2.3 Call Terminated


Triggered when a call is terminated or if it fails.

Syntax
void callTerminated(AudioCodesSession call, SipMessage message, String cause);

Parameters
 AudioCodesSession: The call session object.
 SipMessage [The BYE SIP message; optional, might be 'null']

3.2.4 Outgoing Call Progress


Triggered when a SIP 'trying' response or a SIP 'ringing' response is received.

Syntax
void outgoingCallProgress(AudioCodesSession call, SipMessage response);

Parameters
 AudioCodesSession: The call session object
 SipMessage: The Ringing / Trying SIP message

3.2.5 callHoldStateChanged
Triggered when a SIP local or remote hold state changes (incoming or outgoing re-
INVITE).

Syntax
void callHoldStateChanged(AudioCodesSession call, Boolean isHold, Boolean isRemote);

Parameters
 AudioCodesSession: The call session object
 isHold: Hold (true) or Un-Hold (false)
 IsRemote: Initiator remote side (true) or local side (false)

Version 1.15 65 WebRTC


WebRTC Web Browser Client

3.2.6 callIncomingReinvite
Triggered when the phone receives a re-INVITE. The callback is optional. The callback is
called twice:
 When the phone receives a re-INVITE (argument start=true)
 After the phone sends an OK to the re-INVITE (argument start=false)
The callback can be used to check the phone, after the re-INVITE starts receiving video to
update the video controls GUI.

Syntax
void callIncomingReinvite(AudioCodesSession call, Boolean start, SipMessage request);

Parameters
 AudioCodesSession: The call session object
 start: Received re-INVITE (true) or sent OK response to re-INVITE (false)
 Request: Re-INVITE request, set then start = true

3.2.7 transferorNotification
Triggered after the phone starts the blind call transfer process, when the sent REFER was
accepted or rejected, and when the NOTIFY message with the transfer result was
received.
The callback is optional and should only be used if the phone can initiate a call transfer.

Syntax
void transferorNotification(AudioCodesSession call, integer state)

Parameters
 AudioCodesSession [The call session object]
 state [integer]
 -1: Transfer failed (REFER was rejected or receive NOTIFY with >= 300)
After this, the phone should un-hold the current call.
 0: Transfer progress (receive NOTIFY 1xx)
After this, the phone should un-hold the current call.
 1: Transfer succeeds (receive NOTIFY 2xx).
After this, the phone should terminate the current call.

3.2.8 transfereeRefer
Triggered when the phone receives a SIP REFER message. In the callback, the developer
can check REFER message headers and can accept or reject an incoming REFER
message.
The callback is optional and should be used only if the phone supports call transfer as the
transferee.

API Reference Guide 66 Document, #, LTRT-14054


API Reference Guide 2. API Classes

Syntax
Boolean transfereeRefer(AudioCodesSession call,SipMessage refer);

Parameters
 AudioCodesSession: The call session object
 refer: REFER request

Return Value
 accept incoming REFER: accept (true) or reject (false)

3.2.9 transfereeCreatedCall
When the phone receives a REFER message, it calls the address extracted from the
Refer-To header. The developer should use the callback to obtain the reference to the
newly created call object. The callback is optional and should be used only if the phone
supports call transfer as the transferee.

Syntax
void transfereeCreatedCall(AudioCodesSession call);

Parameters
 AudioCodesSession [Newly created call session object]

3.2.10 incomingNotify
Receives an incoming ‘out of dialog’ or ‘in dialog’ NOTIFY request. The callback is optional
and should be used only if the SDK developer wants the phone to receive NOTIFY
messages.

Syntax
Boolean incomingNotify(AudioCodesSession call, String eventName, Object from, String
contentType, String body, SipMessage request)

Parameters
 AudioCodesSession: The call session object: null for out of dialog NOTIFY
 String: event name: Value of Event header
 From object: Object with parameters: user, host, displayName: null or string
 String: content-type value of Content-Type header or null
 String: optional body or null
 SipMessage: NOTIFY request

Return Values
true: Accept incoming NOTIFY, send NOTIFY OK
false: Use default JsSIP NOTIFY processing

Version 1.15 67 WebRTC


WebRTC Web Browser Client

3.2.11 incomingMessage
Receives an incoming ‘out of dialog’ MESSAGE request. The callback is optional and
should be used only if the SDK developer wants the phone to receive SIP MESSAGE
requests.

Syntax
void incomingMessage(AudioCodesSession call, Object from, String contentType, String body,
SipMessage request)

Parameters
 call [AudioCodesSession]: Always null because its currently implemented based on
outside of the dialog MESSAGE
 From object: Object with parameters: user [String], host [String], displayName: null or
String
 content-type [string]: Value of Content-Type header or null
 Optional body or null [string]
 SipMessage [MESSAGE request]

3.2.12 incomingInfo
Receives an incoming ‘in dialog’ INFO request. The callback is optional and should be
used only if the SDK developer wants the phone to receive SIP INFO requests.

Syntax
void incomingInfo(AudioCodesSession call, Object from, String contentType, String body,
SipMessage request)

Parameters
 call [AudioCodesSession]: The call session object
 From object: Object with parameters: user [String], host [String], displayName: null or
String
 content-type [string]: Value of Content-Type header or null
 Optional body or null [string]
 SipMessage [INFO request]

      

API Reference Guide 68 Document, #, LTRT-14054


API Reference Guide 2. API Classes

3.2.13 callScreenSharingEnded
Notifiies that a screen sharing video stream is closed.
It can be closed when:
 - called method stopScreenSharing.
 - pressed Chrome built-in button “Stop sharing”.
 - the call using screen sharing is terminated.

The callback can be used for control phone GUI.

Syntax
void callScreenSharingEnded(call, stream)

Parameters
 call [AudioCodesSession]: The call session object
 stream [MediaStream]: The media stream created by phone.openScreenSharing().

Version 1.15 69 WebRTC


WebRTC Web Browser Client

3.2.14 incomingSubscribe
Receives an incoming SUBSCRIBE request. The callback is optional and should be used
only if the SDK developer wants the phone to receive SIP SUBSCRIBE requests.

Syntax
int incomingSubscribe(subscribe, eventName, accepts)

Parameters
 subscribe [IncomingRequest]: The SUBSCRIBE SIP request
 eventName [string]: Event header value.
 Accepts [array of string]: Values of accept headers.

Return Value
responseCode >0: Reject incoming SUBSCRIBE with the SIP response code.
0: Accept incoming SUBSCRIBE request.
The request used to create subscribe dialog via method subscribe().

API Reference Guide 70 Document, #, LTRT-14054


API Reference Guide 2. API Classes

This page is intentionally left blank.

Version 1.15 71 WebRTC


WebRTC Web Browser Client

4 Use Examples
This section provides examples that can guide your implementation.

4.1 User Agent: Create Instance, Set Server and Account


let phone = new AudioCodesUA(); // phone API
phone.setServerConfig(['wss://webrtclab.audiocodes.com'], 'audiocodes.com');
phone.setAccount('Igor', 'Igor Kolosov', '<user_password string>');

4.2 User Agent: Set Listeners (Callbacks)


phone.setListeners({
loginStateChanged: function(isLogin, cause) {Your code},
outgoingCallProgress: function(call, response) { Your code },
callTerminated: function(call, message, cause) { Your code },
callConfirmed: function(call, message, cause) { Your code },
callShowStreams: function(call, localStream, remoteStream) { Your code },
incomingCall: function(call, invite) { Your code }
callHoldStateChanged(call, isHold, isRemote){ Your code }
});

4.3 User Agent Init: Connection to SBC Server and Login


phone.init(true);

4.4 Make a Call


let activeCall = phone.call(phone.VIDEO, '[email protected]');

4.5 Send DTMF During Call


activeCall.sendDTMF('9');

4.6 Mute / Unmute During Call


activeCall.muteAudio(true);
activeCall.muteAudio(false);

4.7 Accept Incoming Call


activeCall.answer(phone.VIDEO);

API Reference Guide 72 Document, #, LTRT-14054


API Reference Guide 2. API Classes

4.8 Reject Incoming Call


activeCall.reject();

4.9 Terminate a Call


activeCall.terminate();

4.10 Use of Remote Streams Video


// set remote video html element
document.getElementById('remote_video').srcObject = remoteStream;

4.11 Restore Call after Page Refresh


Before closing the page, the 'beforeunload' event is called. In this event, the client checks if
there's an active call and stores the relevant data in the local storage for further use.
window.addEventListener('beforeunload', onBeforeUnload);

function onBeforeUnload(){
if (activeCall !== null && activeCall.isEstablished()) {
let data = {
callTo: activeCall.data['_user'],
video: activeCall.getVideoState(),
replaces: activeCall.getReplacesHeader(),
time: new Date().getTime(),
hold: `${activeCall.isLocalHold() ? 'local' : ''}$
{activeCall.isRemoteHold() ? 'remote' : ''}`,
mute: `${activeCall.isAudioMuted() ? 'audio' : ''}
${activeCall.isVideoMuted() ? 'video' : ''}`
}
localStorage.setItem('phoneRestoreCall',
JSON.stringify(data));
}
}
After reloading the page and registering on the SBC server, the client checks if there was
an active call and restores it.

let data = localStorage.getItem('phoneRestoreCall');


if( data !== null ){
localStorage.removeItem('phoneRestoreCall');
let r = JSON.parse(data);
let delay = Math.ceil(Math.abs(r.time - new Date().getTime())/1000);
if( delay > 20 ){ // Call can be restored only 20 sec.
console.log('Cannot restore call, delay is too big');
} else {
console.log('Try restore call...');
activeCall = phone.call(r.video === 'sendrecv' || r.video === 'sendonly' ? phone.VIDEO :
phone.AUDIO, r.callTo, ['Replaces: ' + r.replaces]);
}

Version 1.15 73 WebRTC


WebRTC Web Browser Client

4.12 Set Custom Logger


The following shows an example of forwarding the logs to a specific destination using a
custom logger function.
phone.setAcLogger(ac_log); // Set AudioCodes API logger phone.setJsSipLogger(jssip_log);
// Set JsSIP API logger

// Add time stamp and color function


function ac_log() {
let args = [].slice.call(arguments); console.log.apply(console, [createTimestamp() + '%c'
+
args[0]].concat(['color: BlueViolet;'], args.slice(1)));
}
// Add time stamp. function
function jssip_log() {
let args = [].slice.call(arguments); console.log.apply(console, [createTimestamp() +
args[0]].concat(args.slice(1)));
}

4.13 Getting Statistics


The following is an example for statistics retrieval using RTCPeerConnection and an
example output to the console for outband-rtp and inbound-rtp.

Note: WebRTC API is used in the example.

SDK API can also be used.


See the getWR().connection.getStats() method.

function printCallStats() {
    if (activeCall === null) {
        ac_log('activeCall is null');
        return;
    }
    let conn = activeCall.getRTCPeerConnection();
    let str = '';
    conn.getStats(null).then(report=>report.forEach(now=>{
        switch (now.type) {
        case 'outbound-rtp':
        case 'inbound-rtp':
            //case 'track':
            //case 'stream':

            str += ' {';


            let first = true;
            for (let key of Object.keys(now)) {
                if (first)

API Reference Guide 74 Document, #, LTRT-14054


API Reference Guide 2. API Classes

                    first = false;


                else
                    str += ',';
                str += (key + '=' + now[key]);
            }
            str += '} ';
            break;
        default:
            break;
        }
    }
    )).then(()=>{
        ac_log('call stats: ' + str);
    }
    ).catch((err)=>{
        ac_log('stat error', err);
    }
    );
}

4.14 Incoming Call with Replaces Header


If the incoming INVITE contains a Replaces header (that points to an existing open call) in
incomingCall callback argument, then replacedCall will be not null.
In the case where the programmer terminates the replaced call and automatically answers
the incoming call, the incoming call visually (in GUI panel or window) replaces the
terminated call.
incomingCall: function (call, invite, replacedCall) {

// If received INVITE with Replaces header


if (replacedCall !== null) {
ac_log('phone: incomingCall, INVITE with Replaces');

// close the replaced call.


replacedCall.data['terminated_replaced'] = true;
replacedCall.terminate();

// auto answer to replaces call.


activeCall = call;
activeCall.data['open_replaced'] = true;

let videoOption = replacedCall.hasVideo() ? phone.VIDEO :


(replacedCall.hasReceiveVideo() ? phone.RECVONLY_VIDEO: phone.AUDIO);
activeCall.answer(videoOption);
return;
}

Version 1.15 75 WebRTC


WebRTC Web Browser Client

4.15 Incoming Call with Custom Headers


The incoming INVITE may contain custom SIP headers. For example, using the header
Alert-Info. To parse such a header, the programmer may write their own SIP header
parser. The example below uses the custom AlertInfo parser that is defined in utils.js.
incomingCall: function (call, invite, replacedCall) {

....
// Can be used custom header in incoming INVITE
// ------ begin of Alert-Info auto answer example ----
// JsSIP parse Alert-Info as raw string. We use custom parser defined in utils.js
let alertInfo = new AlertInfo(invite);
ac_log(`alert-info header ${alertInfo.exists() ? ' exists' : 'does not exist'}`);
if (alertInfo.hasAutoAnswer()) {
ac_log(`alert-info delay=${alertInfo.getDelay()}`); // currently ignored
ac_log('*** Used Alert-Info Auto answer ***');

let videoOption = call.hasVideo() ? (hasCamera ? phone.VIDEO :


phone.RECVONLY_VIDEO) : phone.AUDIO;
guiAnswerCall(videoOption);
return;
}
//------ end of Alert-Info auto answer example ----

API Reference Guide 76 Document, #, LTRT-14054


API Reference Guide 2. API Classes

This page is intentionally left blank.

Version 1.15 77 WebRTC


WebRTC Web Browser Client

5 Tutorial
You can find a useful tutorial with AudioCodes-provided Web RTC examples at
https://webrtcdemo.audiocodes.com/sdk/webrtc-api-base/examples/tutorial.html.

API Reference Guide 78 Document, #, LTRT-14054


International Headquarters
1 Hayarden Street,
Airport City
Lod 7019900, Israel
Tel: +972-3-976-4000
Fax: +972-3-976-4040

AudioCodes Inc.
200 Cottontail Lane
Suite A101E
Somerset NJ 08873
Tel: +1-732-469-0880
Fax: +1-732-469-2298

Contact us: https://www.audiocodes.com/corporate/offices-worldwide


Website: https://www.audiocodes.com/

©2021 AudioCodes Ltd. All rights reserved. AudioCodes, AC, HD VoIP, HD VoIP Sounds Better, IPmedia, Mediant,
MediaPack, What’s Inside Matters, OSN, SmartTAP, User Management Pack, VMAS, VoIPerfect, VoIPerfectHD, Your
Gateway To VoIP, 3GX, VocaNom, AudioCodes One Voice, AudioCodes Meeting Insights, AudioCodes Room
Experience and CloudBond are trademarks or registered trademarks of AudioCodes Limited. All other products or
trademarks are property of their respective owners. Product specifications are subject to change without notice

Document, #, LTRT-14054

You might also like