mediasoup

/ home / Documentation / v2 / mediasoup-client / API

mediasoup-client v2 API

mediasoupClient

The top-level module exported by the mediasoup-client library.

import * as mediasoupClient from "mediasoup-client";

or

const mediasoupClient = require("mediasoup-client");

Dictionaries

DeviceInfo

Field Type Description
flag String Browser/device identifier.
name String Browser/device descriptive name (taken from User-Agent.
version String Browser/device version.
bowser Object Object produced by the _detect() method of the bowser library.

Current flag values can be:

  • “chrome”
  • “firefox”
  • “safari”
  • “msedge”
  • “opera”
  • custom (see setDeviceHandler)

Properties

mediasoupClient.internals

Exposes the internals property.

Functions

mediasoupClient.setDeviceHandler(handler, metadata)

Set a custom device handler that mediasoup-client will use instead of any builtin one.

Argument Type Description Required Default
handler DeviceHandler Custom device handler. Yes  
metadata DeviceInfo Custom device info. Yes  

mediasoupClient.isDeviceSupported()

Returns a Boolean indicating if the current browser/device is supported by mediasoup-client.

mediasoupClient.getDeviceInfo()

Returns a DeviceInfo Object with the browser/device information.

mediasoupClient.checkCapabilitiesForRoom(roomRtpCapabilities)

Checks the audio/video capabilities of the current device/browser for the remote room given its RTP capabilities.

It returns a Promise that resolves to an Object with audio and video Booleans, indicating whether sending and receiving audio/video is possible once joined in that room.

Argument Type Description Required Default
roomRtpCapabilities RTCRtpCapabilities Room RTP capabilities. Yes  

This method is useful in the scenario in which the application wishes to request the user with mic/webcam permissions before joining the room. By running this method before, the application could avoid requesting webcam permission to the user if his browser does not support the video codec of the room.

Classes

mediasoupClient.Room

Exposes the Room class.

Room

A room is the local representation of a remote Room in mediasoup plus our own peer joining it.

For more information, check the Glossary section.

Dictionaries

RoomOptions

Field Type Description Required Default
roomSettings Object Remote room settings. If given it must include a rtpCapabilities entry (RTCRtpCapabilities of the remote room). No  
requestTimeout Number Timeout for mediasoup protocol sent requests (in milliseconds). No 10000 (10 seconds)
transportOptions TransportOptions Options for created transports. No  
turnServers sequence<RTCIceServer> Array of TURN servers. No []
iceTransportPolicy String The ICE transport policy. No “all”
rtcAudioJitterBufferMaxPackets Number Experimental feature in libwebrtc for audio jitter. No  
rtcAudioJitterBufferMinDelayMs Number Experimental feature in libwebrtc for audio jitter. No  
spy Boolean Join as spy peer (other peers won't see this peer) No false

If roomSettings is given (so it's an Object with rtpCapabilities) mediasoup-client will not request them when room.join() is called.

You can manually get the server side room's RTP capabilities via the room.rtpCapabilities getter.

Here you have a chance to mangle those room RTP capabilities and remove/reorder codecs (to force this mediasoup-client room instance to use a preferred video codec and so on).

It's up to the application server running mediasoup whether a peer with spy: true must be allowed to join a room or not. The server can do this by inspecting the mediasoup protocol request with method: 'join'.

For more inforrmation, see the mediasoup protocol and the usage example in server side.

Constructor

Argument Type Description Required Default
options RoomOptions Room options. No  

Usage example:

const room = mediasoupClient.Room(
  {
    requestTimeout : 8000
  });

Properties

room.joined

  • Read only

A Boolean indicating whether the room has been joined.

room.closed

  • Read only

A Boolean indicating whether the room has been closed.

room.peerName

  • Read only.

An String representing the name of own our Peer.

room.transports

  • Read only

An Array with our list of Transport instances in the room.

room.producers

  • Read only

An Array with our list of Producer instances in the room.

room.peers

  • Read only

An Array with the list of remote Peer instances in the room.

Methods

room.join(peerName, [appData])

Start the procedures to join a remote room. Returns a Promise resolving with an Array of remote Peer instances already in the room.

Argument Type Description Required Default
peerName String My Peer name. Yes  
appData Any Custom app data. No  

Usage example:

room.join("alice")
  .then((peers) =>
  {
    console.info("room joined");
  });

Once the Promise returned by join() resolves, it's recommended to immediately iterate all the peers the Promise resolves with, and also all the consumers in each peer so they can be enabled for media reception.

room.leave([appData])

Leaves the room and triggers a close event.

Argument Type Description Required Default
appData Any Custom app data. No  

room.receiveNotification(notification)

Receive a mediasoup protocol notification payload (generated by mediasoup).

Argument Type Description Required Default
notification Object mediasoup protocol notification. Yes  

The method does not return anything.

room.canSend(kind)

Whether we can send the given kind of media (it depends on the available room and device codecs).

Argument Type Description Required Default
kind String Media kind (“audio” or “video”). Yes  

room.createTransport(direction, [appData])

Creates a new Transport for sending or receiving audio/video.

Argument Type Description Required Default
direction String Direction of the media (“send” or “recv”). Yes  
appData Any Custom app data. No  

room.createProducer(track, [options], [appData])

Creates a new Producer for the given audio/video track.

Argument Type Description Required Default
track MediaStreamTrack Audio/video track. Yes  
options ProducerOptions Options for the producer. No  
appData Any Custom app data. No  

Usage example:

let micProducer;
let webcamProducer;

navigator.mediaDevices.getUserMedia({ audio: true, video: true })
  .then((stream) =>
  {
    const audioTrack = stream.getAudioTracks()[0];
    const videoTrack = stream.getVideoTracks()[0];

    micProducer = room.createProducer(audioTrack);
    webcamProducer = room.createProducer(videoTrack);
  });

Within the new Producer, the given track is internally cloned, so the application can safely stop() the original track.

The above is not true in react-native-webrtc because it does not implement track.clone() and, hence, the track handled by the Producer is the original one and MUST NOT be stopped by the application.

room.restartIce()

Restarts all the Transport instances by following ICE rules. Useful when detecting IP change.

room.getTransportById(name)

Retrieves the Transport with the given id, or undefined if not found.

Argument Type Description Required Default
id Number Transport id. Yes  

room.getProducerById(name)

Retrieves the Producer with the given id, or undefined if not found.

Argument Type Description Required Default
id Number Producer id. Yes  

room.getPeerByName(name)

Retrieves the remote Peer with the given name, or undefined if not found.

Argument Type Description Required Default
name String Peer name. Yes  

Events

The Room class inherits from EventEmitter.

room.on(“close”, fn(appData))

Emitted when the room is closed or when our peer leaves it.

Argument Type Description
appData Any Custom app data.

room.on(“request”, fn(request, callback, errback))

Emitted when a new mediasoup protocol request must be sent to mediasoup.

Argument Type Description
request Object mediasoup protocol request.
callback Function Function that must be called with the mediasoup protocol response received from mediasoup as single argument.
errback Function Function that must be called with an error (Error instance or String) if the request failed for any reason.

Usage example:

room.on("request", (request, callback, errback) =>
{
  myChannel.send({ type: "mediasoup-request", body: request })
    .then((response) =>
    {
      // Success response, so pass the mediasoup response to the local Room.
      callback(response.body);
    })
    .catch((error) =>
    {
      // Error response, so pass the error to the local Room.
      errback(error);
    });
});

room.on(“notify”, fn(notification))

Emitted when a new mediasoup protocol notification must be sent to mediasoup.

Argument Type Description
notification Object mediasoup protocol notification.

Usage example:

room.on("notify", (notification) =>
{
  myChannel.send({ type: 'mediasoup-notification', body: notification });
});

room.on(“newpeer”, fn(peer))

Emitted when a new remote peer joins the room.

Argument Type Description
peer Peer New remote peer.

When the newpeer event is fired, the application should immediately iterate all the consumers in the new peer if it wishes to enable them.

Transport

A transport represents a path, negotiated via ICE and DTLS, for sending or receiving audio/video RTP.

For more information, check the Glossary section.

Internally, the transport runs a specific handler depending on the underlying browser/device. This may be a RTCPeerConnection with Plan-B, or Unified-Plan, using legacy or modern WebRTC API, or even a set of RTCIceTransport, RTCDtlsTransport, RTCRtpSender, RTCRtpReceiver instances when the browser/device runs ORTC inside.

Dictionaries

TransportOptions

Options for a Transport in mediasoup (server side).

Field Type Description Required Default
udp Boolean Offer UDP ICE candidates. No true
tcp Boolean Offer TCP ICE candidates. No true
preferIPv4 Boolean Prefer IPv4 over IPv6 ICE candidates. No false
preferIPv6 Boolean Prefer IPv6 over IPv4 ICE candidates. No false
preferUdp Boolean Prefer UDP over TCP ICE candidates. No false
preferTcp Boolean Prefer TCP over UDP ICE candidates. No false

Enums

ConnectionState

Value Description
“new” ICE procedures not initiated yet.
“connecting” ICE procedures initiated.
“connected” ICE connected.
“failed” ICE procedures failed.
“disconnected” ICE connection was temporaty closed.
“closed” ICE state when the transport has been closed.

Properties

transport.id

  • Read only

Unique identifier (Number).

transport.closed

  • Read only

A Boolean indicating whether the transport has been closed.

transport.appData

  • Read-write

Custom data set by the application.

transport.direction

  • Read only

A String (“send” or “recv”) representing the direction of the media over this transport.

transport.connectionState

  • Read only

The ConnectionState of the underlying RTCPeerConnection or RTCIceTransport.

transport.handler

  • Read only

The DeviceHandler used by the transport.

Methods

transport.close([appData])

Closes the transport and triggers a close event.

Argument Type Description Required Default
appData Any Custom app data. No  

transport.enableStats([interval = 1000])

Subscribes the transport to RTC stats retrieved via the stats event.

Argument Type Description Required Default
interval Number Stats retrieval interval (in milliseconds). No 1000

Check the RTC stats section for more details.

transport.disableStats()

Closes the subscription to RTC stats for this transport.

Events

The Transport class inherits from EventEmitter.

transport.on(“close”, fn(originator, appData))

Emitted when the transport is closed.

Argument Type Description
originator String “local” or “remote”.
appData Any Custom app data.

transport.on(“connectionstatechange”, fn(connectionstate))

Emitted when the underlying ICE connection state changes.

Argument Type Description
connectionstate ConnectionState The new connection state.

transport.on(“stats”, fn(stats))

Emitted when RTC stats are retrieved.

Argument Type Description
stats sequence<Object> RTC stats.

Producer

A producer represents an audio/video media track sent to the room.

For more information, check the Glossary section.

Dictionaries

ProducerOptions

Field Type Description Required Default
simulcast SimulcastOptions|Boolean Simulcast options. No  

If simulcast is set to true, a default value will be set. Note that in some browsers there is no API to specify bitrates for simulcast streams (such as in Chrome family) so passing an a SimulcastOptions Object here is the same as just setting it to true.

SimulcastOptions

Options for simulcast streams.

Field Type Description Required Default
low Number Bitrate (in kbps) of the lowest stream. No 100000
medium Number Bitrate (in kbps) of the medium stream. No 300000
high Number Bitrate (in kbps) of the highest stream. No 1500000

Given values are just a hint. Certain browsers don't even expose an API to define the bitrate of each simulcast layer.

Properties

producer.id

  • Read only

Unique identifier (Number).

producer.closed

  • Read only

A Boolean indicating whether the producer has been closed.

producer.appData

  • Read-write

Custom data set by the application.

producer.kind

  • Read only

The media kind (“audio” or “video”) handled by the producer.

producer.track

  • Read only

The MediaStreamTrack internally handled by the producer.

producer.originalTrack

  • Read only

The original MediaStreamTrack given to the producer (not internally used).

producer.transport

  • Read only

The Transport assigned to this producer (if any).

producer.rtpParameters

  • Read only

An Object with the effective RTP parameters of the producer, miming the syntax of RTCRtpParameters in ORTC.

producer.locallyPaused

  • Read only

Boolean indicating whether this producer has been locally paused.

producer.remotelyPaused

  • Read only

Boolean indicating whether this producer has been remotely paused.

producer.paused

  • Read only

Boolean indicating whether this producer has been locally or remotely paused.

Methods

producer.close([appData])

Closes the producer and triggers a close event.

Argument Type Description Required Default
appData Any Custom app data. No  

producer.send(transport)

Enables sending RTP for this producer by providing a transport. It returns a Promise.

Argument Type Description Required Default
transport Transport transport with direction “send”. Yes  

producer.pause([appData])

Pauses the producer locally, meaning that no RTP will be sent to the room.

Argument Type Description Required Default
appData Any Custom app data. No  

producer.resume([appData])

Resumes the producer locally, meaning that RTP will be relayed again to the room (unless the producer was also remotely paused).

Argument Type Description Required Default
appData Any Custom app data. No  

producer.replaceTrack(track)

Replaces the audio/video track being sent to the room.

Argument Type Description Required Default
track MediaStreamTrack New audio/video track. Yes  

producer.enableStats([interval = 1000])

Subscribes the producer to RTC stats retrieved via the stats event.

Argument Type Description Required Default
interval Number Stats retrieval interval (in milliseconds). No 1000

Check the RTC stats section for more details.

producer.disableStats()

Closes the subscription to RTC stats for this producer.

Events

The Producer class inherits from EventEmitter.

producer.on(“close”, fn(originator, appData))

Emitted when the producer is closed.

Argument Type Description
originator String “local” or “remote”.
appData Any Custom app data.

producer.on(“pause”, fn(originator, appData))

Emitted when the producer is locally or remotely paused.

Argument Type Description
originator String “local” or “remote”.
appData Any Custom app data.

producer.on(“resume”, fn(originator, appData))

Emitted when the producer is locally or remotely resumed.

Argument Type Description
originator String “local” or “remote”.
appData Any Custom app data.

producer.on(“trackended”, fn())

Emitted when the internally managed track's is stopped (useful to detect microphone or webcam disconnection/failures). The producer is not automatically closed (it's up to the application to close it or not).

producer.on(“handled”, fn())

Emitted when a transport is given to this producer.

producer.on(“unhandled”, fn())

Emitted when the associated transport is closed.

producer.on(“stats”, fn(stats))

Emitted when RTC stats are retrieved.

Argument Type Description
stats sequence<Object> RTC stats.

Peer

A peer is the local representation of a remote peer.

For more information, check the Glossary section.

Properties

peer.name

  • Read only

The name (String) of the remote peer.

peer.closed

  • Read only

A Boolean indicating whether the peer has been closed.

peer.appData

  • Read-write

Custom data set by the remote application.

peer.consumers

  • Read only

An Array with the list of Consumer instances associated to the remote peer in the order in which they were created.

Methods

peer.getConsumerById(id)

Retrieves the Consumer with the given id, or undefined if not found.

Argument Type Description Required Default
id Number Consumer id. Yes  

Events

The Peer class inherits from EventEmitter.

peer.on(“close”, fn())

Emitted when the remote peer is closed or leaves the room.

peer.on(“newconsumer”, fn(consumer))

Emitted when a new consumer is created for receiving new media produced by the remote peer.

Argument Type Description
consumer Consumer New consumer.

Consumer

A consumer represents an audio/video media track received from the room.

For more information, check the Glossary section.

Properties

consumer.id

  • Read only

Unique identifier (Number).

consumer.closed

  • Read only

A Boolean indicating whether the consumer has been closed.

consumer.appData

  • Read-write

Custom data set by the application.

consumer.kind

  • Read only

The media kind (“audio” or “video”) handled by the consumer.

consumer.rtpParameters

  • Read only

An Object with the effective RTP parameters of the consumer, miming the syntax of RTCRtpParameters in ORTC.

consumer.track

  • Read only

The MediaStreamTrack internally handled by the consumer.

It is undefined if receive() was not called before.

consumer.peer

  • Read only

The remote Peer instance producing the media.

It is undefined if this is not a Consumer associated to a remote peer.

consumer.supported

  • Read only

A Boolean indicating whether our browser/device can enable this Consumer. If we don't support the audio/video codec this won't be true.

consumer.transport

  • Read only

The Transport assigned to this consumer (if any).

consumer.locallyPaused

  • Read only

Boolean indicating whether this consumer has been locally paused.

consumer.remotelyPaused

  • Read only

Boolean indicating whether this consumer has been remotely paused.

consumer.paused

  • Read only

Boolean indicating whether this consumer has been locally or remotely paused.

consumer.preferredProfile

  • Read only

String indicating the preferred RTP profile set via consumer.setPreferredProfile().

consumer.effectiveProfile

  • Read only

String indicating the effective current RTP profile of this consumer.

Methods

consumer.close([appData])

Closes the consumer and triggers a close event.

Argument Type Description Required Default
appData Any Custom app data. No  

consumer.receive(transport)

Enables receiving RTP for this consumer by providing a transport. It returns a Promise resolving to a remote MediaStreamTrack.

Argument Type Description Required Default
transport Transport transport with direction “recv”. Yes  

Usage example:

const stream = new MediaStream();

consumer.receive(recvTransport)
  .then((track) =>
  {
    stream.addTrack(track);
    videoElem.srcObject = stream;
  });

consumer.pause([appData])

Pauses the consumer locally, meaning that no RTP will be received from the room.

Argument Type Description Required Default
appData Any Custom app data. No  

consumer.resume([appData])

Resumes the consumer locally, meaning that RTP will be received again from the room (unless the consumer or its remote source was also remotely paused).

Argument Type Description Required Default
appData Any Custom app data. No  

consumer.setPreferredProfile(profile)

Set the given RTP profile as the desired profile. No profile higher than the given one will become effective profile for this consumer.

For more information, check the Glossary section.

Argument Type Description Required Default
profile String Preffered RTP profile. Yes  

consumer.enableStats([interval = 1000])

Subscribes the consumer to RTC stats retrieved via the stats event.

Argument Type Description Required Default
interval Number Stats retrieval interval (in milliseconds). No 1000

Check the RTC stats section for more details.

consumer.disableStats()

Closes the subscription to RTC stats for this consumer.

Events

The Consumer class inherits from EventEmitter.

consumer.on(“close”, fn(originator, appData))

Emitted when the consumer is closed.

Argument Type Description
originator String “local” or “remote”.
appData Any Custom app data.

consumer.on(“pause”, fn(originator, appData))

Emitted when the consumer is locally or remotely paused.

Argument Type Description
originator String “local” or “remote”.
appData Any Custom app data.

consumer.on(“resume”, fn(originator, appData))

Emitted when the consumer is locally or remotely resumed.

Argument Type Description
originator String “local” or “remote”.
appData Any Custom app data.

consumer.on(“effectiveprofilechange”, fn(profile))

Emitted when the effective profile changes.

Argument Type Description
profile String Current effective RTP profile.

consumer.on(“handled”, fn())

Emitted when a transport is given to this consumer.

consumer.on(“unhandled”, fn())

Emitted when the associated transport is closed.

consumer.on(“stats”, fn(stats))

Emitted when RTC stats are retrieved.

Argument Type Description
stats sequence<Object> RTC stats.