opensips-js
v0.1.36
Published
The JS package for opensips
Readme
title: Getting started description: The Opensips JS library and its expansive ecosystem offer developers a powerful and flexible solution for integrating Opensips protocol functionalities into a multitude of applications. navigation: title: Getting Started
Getting started
Installation
Using npm:
$ npm i opensips-jsUsing via CDN:
You can include the OpensipsJS library directly in your HTML file using a CDN like UNPKG or jsDelivr. This is especially useful for quick prototyping or when you don't want to set up a build environment.
Add the following script tag to your HTML file:
<script src="https://cdn.opensipsjs.org/opensipsjs/v0.1.1/opensips-js.iife.js"></script>This will load the library and attach the OpensipsJS class to the global window object as OpensipsJS.
Usage
Using npm (ES Modules):
Firstly lets import the library and create the OpenSIPS instance:
import OpenSIPSJS from 'opensips-js'
const openSIPSJS = new OpenSIPSJS({
configuration: {
session_timers: false,
uri: 'sip:extension_user@domain',
// --- Use password or authorization_jwt to authorize
password: 'password',
// or
authorization_jwt: 'token',
},
socketInterfaces: [ 'wss://domain' ],
pnExtraHeaders: {
'pn-provider': 'acme',
'pn-param': 'acme-param',
'pn-prid': 'ZH11Y4ZDJlMNzODE1NgKi0K>'
},
sipDomain: 'domain',
sipOptions: {
session_timers: false,
extraHeaders: [ 'X-Bar: bar' ],
pcConfig: {},
},
modules: [ 'audio', 'video', 'msrp' ]
})
// Then you can work with the appropriate modules
opensipsJS.audio
opensipsJS.video
opensipsJS.msrpUsing via CDN:
After including the script via CDN, you can access the OpensipsJS class directly from the global scope.
<!DOCTYPE html>
<html>
<head>
<title>OpensipsJS CDN Usage</title>
</head>
<body>
<!-- Include the library via CDN -->
<script src="https://cdn.opensipsjs.org/opensipsjs/v0.1.1/opensips-js.iife.js"></script>
<script>
// Create an instance of OpensipsJS
const opensipsJS = new OpensipsJS({
configuration: {
session_timers: false,
uri: 'sip:extension_user@domain',
// --- Use password or authorization_jwt to authorize
password: 'password',
// or
authorization_jwt: 'token',
},
socketInterfaces: ['wss://domain'],
pnExtraHeaders: {
'pn-provider': 'acme',
'pn-param': 'acme-param',
'pn-prid': 'ZH11Y4ZDJlMNzODE1NgKi0K>',
},
sipDomain: 'domain',
sipOptions: {
session_timers: false,
extraHeaders: ['X-Bar: bar'],
pcConfig: {},
},
modules: ['audio', 'video', 'msrp'],
});
// Now you can use the modules
opensipsJS.audio;
opensipsJS.video;
opensipsJS.msrp;
</script>
</body>
</html>Note: When using the library via CDN, ensure that you replace 'sip:extension_user@domain', 'password', 'token', and other placeholders with your actual configuration values.
Using ES Modules via CDN:
If you prefer using ES modules in the browser and your environment supports them, you can import the ES module build directly from the CDN.
<!DOCTYPE html>
<html>
<head>
<title>OpensipsJS ES Module CDN Usage</title>
</head>
<body>
<script type="module">
import OpensipsJS from 'https://cdn.opensipsjs.org/opensipsjs/v0.1.1/opensips-js.es.js';\
const opensipsJS = new OpensipsJS({
configuration: {
session_timers: false,
noiseReductionOptions: {
mode: 'dynamic',
noiseThreshold: 0.004
checkEveryMs: 500
noiseCheckInterval: 2000
},
uri: 'sip:extension_user@domain',
// --- Use password or authorization_jwt to authorize
password: 'password',
// or
authorization_jwt: 'token',
},
socketInterfaces: ['wss://domain'],
pnExtraHeaders: {
'pn-provider': 'acme',
'pn-param': 'acme-param',
'pn-prid': 'ZH11Y4ZDJlMNzODE1NgKi0K>',
},
sipDomain: 'domain',
sipOptions: {
session_timers: false,
extraHeaders: ['X-Bar: bar'],
pcConfig: {},
},
modules: ['audio', 'video', 'msrp'],
});
// Use the modules as before
opensipsJS.audio;
opensipsJS.video;
opensipsJS.msrp;
</script>
</body>
</html>Important: When using ES modules via CDN:
- Ensure your browser supports ES modules.
- The
type="module"attribute is necessary in the<script>tag.
OpensipsJS
OpensipsJS instance methods
begin(): OpensipsInstance- start opensipson(event: OpensipsEvent, callback): void- remove event listenersubscribe({type: String, listener: function}): void- subscribe to an event. Available events:new_call,ended,progress,failed,confirmedremoveIListener(type: String): void- remove event listener
OpensipsJS events
| Event | Callback interface | Description |
|---------------------------------|----------------------------------------------------------|-------------------------------------------------------|
| ready | () => {} | Emitted when opensips is initialized |
| changeActiveCalls | (calls: { [key: string]: ICall }) => {} | Emitted when active calls are changed |
| callAddingInProgressChanged | (callId: string / undefined) => {} | Emitted when any call adding state is changed |
| changeAvailableDeviceList | (devices: Array<MediaDeviceInfo>) => {} | Emitted when the list of available devices is changed |
| changeActiveInputMediaDevice | (deviceId: string) => {} | Emitted when active input device is changed |
| changeActiveOutputMediaDevice | (deviceId: string) => {} | Emitted when active output device is changed |
| changeMuteWhenJoin | (value: boolean) => {} | Emitted when mute on join value is changed |
| changeIsDND | (value: boolean) => {} | Emitted when is DND value is changed |
| changeIsMuted | (value: boolean) => {} | Emitted when mute value is changed |
| changeActiveStream | (stream: MediaStream) => {} | Emitted when active stream was changed |
| changeCallVolume | (callId: string, volume: number) => {} | Emits the volume meter's value for each participant |
| currentActiveRoomChanged | (number / undefined) => {} | Emitted when active room is changed |
| addRoom | ({room: IRoom, roomList: {[id: number]: IRoom}}) => {} | Emitted when new room was added |
| updateRoom | ({room: IRoom, roomList: {[id: number]: IRoom}}) => {} | Emitted when room was updated |
| removeRoom | ({room: IRoom, roomList: {[p: number]: IRoom}}) => {} | Emitted when room was deleted |
WebrtcMetricsConfigType
| Parameter | Type | Default |
|----------------|-----------|-------------|
| refreshEvery | number | undefined |
| startAfter | number | undefined |
| startAfter | number | undefined |
| verbose | boolean | undefined |
| pname | string | undefined |
| cid | string | undefined |
| uid | string | undefined |
| record | boolean | undefined |
| ticket | boolean | undefined |
Also, there are next public fields on OpensipsJS instance:
OpensipsJS instance fields
sipDomain: String- returns sip domain
Audio
Audio methods
initCall(target: String, addToCurrentRoom: Boolean, holdOtherCalls: Boolean): void- call to the target. If addToCurrentRoom is true then the call will be added to the user's current roomholdCall(callId: String, automatic?: Boolean): Promise<void>- put call on holdunholdCall(callId: String): Promise<void>- unhold a callterminateCall(callId: String): void- terminate callmoveCall(callId: String, roomId: Number): Promise<void>- Same as callChangeRoom. Move call to the specific roomtransferCall(callId: String, target: String): void- transfer call to targetmergeCall(roomId: Number): void- merge calls in specific room. Works only for rooms with 2 calls insidemergeCallByIds(firstCallId: string, secondCallId: string): void- merge 2 calls by their idsanswerCall(callId: String): void- answer a callmute(): void- mute ourselfunmute(): void- unmute ourselfmuteCaller(callId: String): void- mute callerunmuteCaller(callId: String): void- unmute callersetMicrophone(deviceId: String): Promise<void>- set passed device as input device for callssetSpeaker(deviceId: String): Promise<void>- set passed device as output device for callssetActiveRoom(roomId: Number): Promise<void>- switch to the roomsetMicrophoneSensitivity(value: Number): void- set sensitivity of microphone. Value should be in range from 0 to 1setSpeakerVolume(value: Number): void- set volume of callers. Value should be in range from 0 to 1setDND(value: Boolean): void- set the agent "Do not disturb" statussetMetricsConfig(config: WebrtcMetricsConfigType): void- set the metric config (used for audio quality indicator)setVADConfiguration(options: Partial<Omit<NoiseReductionOptions, 'vadModule'>>): void- update noise reduction configuration at runtime. RequiresvadModuleto be passed in the constructor, otherwise throws an error
Audio instance fields
sipOptions: Object- returns sip optionsgetActiveRooms: { [key: number]: IRoom }- returns an object of active rooms where key is room id and value is room datasipDomain: String- returns sip domainsipOptions: Object- returns sip optionsgetInputDeviceList: []- returns list of input devicesgetOutputDeviceList: []- returns list of output devicescurrentActiveRoomId: Number- returns current active room idselectedInputDevice: String- returns current selected input device idselectedOutputDevice: String- returns current selected output device idisDND: Boolean- returns if the agent is in "Do not disturb" statusisMuted: Boolean- returns if the agent is muted
Noise Reduction Options (VAD)
Important: Voice Activity Detection (VAD) is an optional feature that requires installing an additional peer dependency. It is NOT compatible with React Native.
Critical: VAD Module Must Be Passed to Constructor
If you plan to use noise reduction features (including setVADConfiguration in runtime), you MUST pass vadModule to the OpenSIPSJS constructor during initialization.
- ✅ Required: Pass
vadModulein the constructor if you want to use noise reduction - ❌ Will throw error: Calling
setVADConfiguration()withoutvadModulein the constructor will throw an error - ⚠️ Cannot be changed later: The
vadModulecannot be set after initialization - it must be provided in the constructor
For Web Applications (with VAD support)
Install the VAD library:
npm install @ricky0123/vad-web
# or
yarn add @ricky0123/vad-webThen import and inject it in your configuration during initialization:
import OpenSIPSJS from 'opensips-js'
import * as VAD from '@ricky0123/vad-web'
const opensipsJS = new OpenSIPSJS({
configuration: {
// ... other configuration
noiseReductionOptions: {
mode: 'dynamic', // or 'enabled'
vadModule: VAD, // ⚠️ REQUIRED: Must be passed here if you plan to use noise reduction
noiseThreshold: 0.004,
checkEveryMs: 500,
noiseCheckInterval: 2000
}
},
// ... rest of configuration
})
// ✅ Now you can use setVADConfiguration
opensipsJS.audio.setVADConfiguration({
mode: 'enabled',
noiseThreshold: 0.005
})For Chrome MV3 Extensions
Chrome Manifest V3 extensions block dynamic imports from external sources at the browser level. To use VAD in a Chrome MV3 extension, you must bundle the VAD assets locally.
1. Copy required files to your extension:
From node_modules/@ricky0123/vad-web/dist/:
silero_vad_legacy.onnxsilero_vad_v5.onnxvad.worklet.bundle.min.js
From node_modules/onnxruntime-web/dist/:
ort-wasm-simd-threaded.mjsort-wasm-simd-threaded.wasm
Place them in your extension directory (e.g., assets/vad/ and assets/onnx/).
Note: The exact ONNX files needed may vary depending on browser capabilities. If you encounter loading errors, you may also need ort-wasm-simd-threaded.jsep.wasm or other variants from the onnxruntime-web/dist/ folder.
2. Configure OpenSIPSJS with local paths:
import OpenSIPSJS from 'opensips-js'
import * as VAD from '@ricky0123/vad-web'
const opensipsJS = new OpenSIPSJS({
configuration: {
// ... other configuration
noiseReductionOptions: {
mode: 'dynamic',
vadModule: VAD,
// Point to locally bundled assets
baseAssetPath: browser.runtime.getURL('assets/vad/'),
onnxWASMBasePath: browser.runtime.getURL('assets/onnx/')
}
},
// ... rest of configuration
})Note: If your extension page is opened via browser.windows.create() or similar (extension's own context), you don't need web_accessible_resources. The extension can access its bundled files directly.
For React Native Applications (VAD not supported)
Simply omit the VAD module and disable noise reduction:
import OpenSIPSJS from 'opensips-js'
const opensipsJS = new OpenSIPSJS({
configuration: {
// ... other configuration
noiseReductionOptions: {
mode: 'disabled' // or omit noiseReductionOptions entirely
}
// NO vadModule needed
},
// ... rest of configuration
})See VAD_USAGE.md and EXAMPLES.md for detailed usage examples.
Configuration Parameters
| Parameter | Type | Default | Description |
|----------------------|----------------------------------|----------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| mode | disabled \| enabled \| dynamic | disabled | Noise reduction mode. Note: enabled and dynamic modes require vadModule to be provided |
| vadConfig | Partial<RealTimeVADOptions> | {} | VAD configuration |
| noiseThreshold | number | 0.004 | Noise threshold |
| noiseCheckInterval | number | 2000 | The interval, used to check if we need to disable/enable outgoing audio every N-milliseconds |
| checkEveryMs | number | 500 | The interval, used inside noiseCheckInterval loop, checks current noise state every N-milliseconds, to define the average noise level. Then on every noiseCheckInterval iteration, the values getting on checkEveryMs will be summed, then divided by it's number and compared to noiseThreshold |
| baseAssetPath | string | https://cdn.jsdelivr.net/npm/@ricky0123/[email protected]/dist/ | Base path for VAD web assets. For Chrome MV3 extensions, use local bundled path via browser.runtime.getURL() |
| onnxWASMBasePath | string | https://cdn.jsdelivr.net/npm/[email protected]/dist/ | Base path for ONNX runtime WASM files. For Chrome MV3 extensions, use local bundled path via browser.runtime.getURL() |
MSRP
MSRP methods
initMSRP(target: String, body: String): void- initialize connection with target contact. Body is the initial message to this target.sendMSRP(sessionId: String, body: String): Promise<void>- send messagemsrpAnswer(sessionId: String)- accept MSRP session invitationmessageTerminate(sessionId: String)- terminate message session
MSRP instance fields
getActiveMessages: { [key: string]: IMessage }- returns an object of active message sessions where key is session id and value is message session data.
Video
Video methods
joinRoom(roomId: String, displayName: String, mediaConstraints: Object): void- join conference roomhangup()- exit roomstartVideo()- turn on camerastopVideo()- turn off camerastartAudio()- mutestopAudio()- unmutestartScreenShare()- start screen sharingstopScreenShare()- stop screen sharingenableScreenShareWhiteboard(enable: boolean, stream: MediaStream)- enable screen share whiteboard. stream parameter is screen share streamenableBokehEffectMask(): Promise<MediaStream>- enable bokeh mask effectenableBackgroundImgEffectMask(): Promise<MediaStream>- enable background image mask effectdisableMask(): Promise<MediaStream>- turn off mask effect. Returns stream without maskingrestartMasking(): Promise<void>- rerun mask effectsetupMaskVisualizationConfig(config: VisualizationConfigType)- setup mask configstartNoiseFilter()- start noise filterstopNoiseFilter()- stop noise filtersetBitrate(bitrate: number)- set bitrate for videoenableWhiteboard(mode: 'whiteboard' | 'imageWhiteboard', enable: boolean, base64Image?: string)- enable whiteboard. if mode is 'imageWhiteboard' then third parameter base64Image is requiredsetupDrawerOptions(options: KonvaDrawerOptions)- setup option for drawersetupScreenShareDrawerOptions(options: KonvaScreenShareDrawerOptions)- setup option for screen share drawer
VisualizationConfigType
| Parameter | Type | Default |
|-----------------------|----------|---------|
| foregroundThreshold | number | 0.5 |
| maskOpacity | number | 0.5 |
| maskBlur | number | 0 |
| pixelCellWidth | number | 10 |
| backgroundBlur | number | 15 |
| edgeBlur | number | 3 |
KonvaDrawerOptions
| Parameter | Type |
|-------------|----------|
| container | number |
| width | number |
| height | number |
KonvaScreenShareDrawerOptions
| Parameter | Type |
|---------------|----------|
| strokeWidth | number |
| strokeColor | string |
Video events
| Event | Callback interface | Description |
|--------------------------|--------------------|-------------------------------------------|
| member:join | (data) => {} | Emitted when new member is joined |
| member:update | (data) => {} | Emitted when member data is changed |
| member:hangup | (data) => {} | Emitted when member leaves the conference |
| hangup | () => {} | Emitted when we leave the conference |
| screenShare:start | () => {} | Emitted when we share a screen |
| screenShare:stop | () => {} | Emitted when we stop a screen sharing |
| reconnect | () => {} | Emitted when reconnecting |
| mediaConstraintsChange | () => {} | Emitted when media constraints change |
| metrics:report | () => {} | Emitted on metric report |
| metrics:stop | () => {} | Emitted when metrics are stopped |
