mediasoup

API

mediasoup

The top-level module exported by the mediasoup module.

const mediasoup = require("mediasoup");

Properties

mediasoup.errors

Provides access to the errors module.

mediasoup.extra

Provides access to the extra module.

mediasoup.webrtc

Provides access to the webrtc module, which exposes a subset of the W3C WebRTC 1.0 API, including classes such as RTCPeerConnection.

Methods

mediasoup.Server(settings)

Returns a new Server instance.

Argument Type Description Required Default
settings ServerSettings Server settings. No  

Usage example:

const server = mediasoup.Server({
    logLevel            : "warn",
    rtcIPv4             : "1.2.3.4",
    rtcIPv6             : false,
    dtlsCertificateFile : "/home/foo/dtls-cert.pem",
    dtlsPrivateKeyFile  : "/home/foo/dtls-key.pem"
  });

Server

A server runs and manages a set of mediasoup worker child processes that handle media realtime-communications (ICE, DTLS, RTP, RTCP, DataChannel, etc.).

Dictionaries

ServerSettings

Field Type Description Required Default
numWorkers Integer Number of child worker processes. No Number of CPU cores in the host
logLevel String Logging level for logs generated by the media worker subprocesses (check the Debugging documentation). Valid values are “debug”, “warn”, “error”. No “debug”
logTags Array Log tags for debugging. Check the list of available tags in Debugging documentation. No [ ]
rtcIPv4 String|Boolean IPv4 for RTC. Valid values are a IPv4, true (auto-detect) and false (disabled). No true
rtcIPv6 String|Boolean IPv6 for RTC. Valid values are a IPv6, true (auto-detect) and false (disabled). No true
rtcAnnouncedIPv4 String Announced IPv4 for RTC. Useful for deployments in server with private IP such as AWS. Valid values are a IPv4. No  
rtcAnnouncedIPv6 String Announced IPv6 for RTC. Useful for deployments in server with private IP such as AWS. Valid values are a IPv4. No  
rtcMinPort Integer Minimun RTC port. No 10000
rtcMaxPort Integer Maximum RTC port. No 59999
dtlsCertificateFile String Path to the DTLS certificate. If unset, a random certificate is generated. No  
dtlsPrivateKeyFile String Path to the DTLS private key. If unset, a random certificate is generated. No  

ServerUpdateableSettings

Field Type Description Required Default
logLevel String Logging level for logs generated by the media worker subprocesses (check the Debugging documentation). Valid values are “debug”, “warn”, “error”. No  
logTags Array Log tags for debugging. Check the list of available tags in Debugging documentation. No  

Properties

server.closed

  • Read only

A boolean indicating whether the server has been closed.

Methods

server.close()

Closes the server, including all its rooms, and triggers a close event.

server.dump()

For debugging purposes. Returns a Promise that resolves to an Object containing the server internals.

{
  "workers" :
  [
    {
      "workerId" : "gijzfkyr#1",
      "rooms"    : []
    },
    {
      "workerId" : "gijzfkyr#2",
      "rooms"    : []
    }
  ]
}

server.updateSettings(settings)

Updates the server settings in runtime. Just a subset of the full ServerSettings can be updated.

Argument Type Description Required Default
settings ServerUpdateableSettings Server settings. No  

server.createRoom(options)

Returns a Promise that resolves to a new Room instance. If something goes wrong the Promise is rejected with the corresponding Error object.

Argument Type Description Required Default
options RoomOptions Room options. Yes  

Usage example:

const options = {
  roomCodecs : [
    {
      kind        : "audio",
      name        : "audio/opus",
      clockRate   : 48000,
      payloadType : 101,
      parameters  :
      {
        useInBandFec : true,
        useDtx       : true
      }
    },
    {
      kind        : "video",
      name        : "video/vp8",
      clockRate   : 90000,
      payloadType : 102
    }
  ]
};

server.createRoom(options)
  .then((room) => {
    console.log("room created: %o", room);
  })
  .catch((error) => {
    console.error("room creation failed: %o", error);
  });

Events

The Server class inherits from EventEmitter.

server.on(“close”, fn(error))

Emitted when the server is closed. In case of error, the callback is called with the corresponding Error object.

server.on("close", (error) => {
  if (error)
    console.error("server closed with error: %o", error);
});

server.on(“newroom”, room)

Emitted when a new room is created.

Argument Type Description
room Room New room.

Room

A room holds a multiparty RTC (Real-Time Communication) conference.

Dictionaries

RoomOptions

Field Type Description Required Default
mediaCodecs sequence<RoomMediaCodec> Media codecs available in the room. Yes.  

RoomMediaCodec

Field Type Description Required Default
mediaCodecs sequence<RtpCodecParameters> The list of media codecs supported by the room. Yes  
  • Feature codecs (such as RTX or FEC) must not be placed into mediaCodecs.
  • Entries in mediaCodecs must not have rtcpFeedback parameter.

AudioLevelInfo

Field Type Description Required Default
peer Peer peer generating audio. Yes  
rtpReceiver RtpReceiver rtpReceiver generating audio. Yes  
audioLevel Integer Audio level in dBov (0 means maximum level, -127 means no audio). Yes  

Properties

room.id

  • Read only

Unique identifier (number).

room.closed

  • Read only

A Boolean indicating whether the room has been closed.

room.peers

  • Read only

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

Methods

room.close()

Closes the room, including all its peers, and triggers a close event.

room.dump()

For debugging purposes. Returns a Promise that resolves to an Object containing the room internals.

room.Peer(name)

Creates and returns a new Peer instance.

Argument Type Description Required Default
name String Peer name. Must be unique within the room. Yes  

Usage example:

const peer = room.Peer("alice");

room.getPeer(name)

Returns a Peer with the given name, or undefined if such a peer does not exist in the room.

Argument Type Description Required Default
name String Peer name. Yes  

Events

The Room class inherits from EventEmitter.

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

Emitted when the room is closed. In case of error, the callback is called with the corresponding Error object.

room.on(“newpeer”, peer)

Emitted when a new peer is created.

Argument Type Description
peer Peer New peer.

room.on(“audiolevels”, fn(audioLevelInfos))

Emitted every 500 ms. Provides information regarding the audio level of each audio rtpReceiver in the room.

Argument Type Description
audioLevelInfos sequence<AudioLevelInfo> Audio level information entries ordered by level (higher first).

Peer

A peer is the local representation of a remote media endpoint that connects to mediasoup and sends/receives media streams. It should be understood in “reverse” order:

  • If a browser wants to send video, its corresponding mediasoup peer will “receive” video.
  • If a browser wants to receive video, its corresponding mediasoup peer will “send” video.

In the context of WebRTC 1.0, such a “remote media endpoint” implies a RTCPeerConnection running in a remote browser.

Properties

peer.id

  • Read only

Unique identifier (number).

peer.closed

  • Read only

A Boolean indicating whether the peer has been closed.

peer.name

  • Read only

The name (String) of the peer.

peer.transports

  • Read only

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

peer.rtpReceivers

  • Read only

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

peer.rtpSenders

  • Read only

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

Methods

peer.close()

Closes the peer, including all its transports, rtpReceivers and rtpSenders, and triggers a close event.

peer.dump()

For debugging purposes. Returns a Promise that resolves to an Object containing the peer internals.

peer.setCapabilities(capabilities)

Argument Type Description Required Default
capabilities RtpCapabilities Peer's RTP capabilities. Yes  

Sets the RTP capabilities of the peer.

This method must be called before creating any RtpReceiver for this peer.

peer.createTransport(options)

Returns a Promise that resolves to a new Transport instance associated to this peer. If something goes wrong the Promise is rejected with the corresponding Error object.

Argument Type Description Required Default
options TransportOptions Transport options. No  

Usage example:

peer.createTransport({ tcp: false })
  .then((transport) => {
    console.log("transport created: %o", transport);
  })
  .catch((error) => {
    console.error("transport creation failed: %o", error);
  });

peer.RtpReceiver(kind, transport)

Returns a new RtpReceiver instance.

Argument Type Description Required Default
kind MediaKind Media kind. Yes  
transport Transport Associated transport. Yes  

Usage example:

const rtpReceiver = peer.RtpReceiver("audio", transport);

Events

The Peer class inherits from EventEmitter.

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

Emitted when the peer is closed. In case of error, the callback is called with the corresponding Error object.

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

Emitted after a succesful call to setCapabilities. It provides the effective RTP capabilities of the peer (after filtering capabilities non supported by the room).

Argument Type Description  
capabilities RtpCapabilities Peer's effective RTP capabilities. Yes

peer.on(“newtransport”, fn(transport))

Emitted when a new transport is created.

Argument Type Description
transport Transport New transport.

peer.on(“newrtpreceiver”, fn(rtpReceiver))

Emitted when a new rtpReceiver is created.

Argument Type Description
rtpReceiver RtpReceiver New rtpReceiver.

peer.on(“newrtpsender”, fn(rtpSender))

Emitted when another peer in the same room creates a new RtpReceiver and calls receive() on it for first time. Also emitted for each already existing RtpReceiver in the room once the peer joins it.

Argument Type Description
rtpSender RtpSender New rtpSender.
peer.on("newrtpsender", (rtpSender) => {
  console.log("new rtpSender: %o", rtpSender);
});

Transport

A transport represents a ICE+DTLS virtual connection over which a remote peer sends and receives media streams.

The Transport instance is created by means of peer.createTransport(). It binds UDP and TCP ports (depending on the given parameters) and waits for ICE Binding Requests coming from the peer. Once ICE procedures are done, DTLS connection must be established.

mediasoup is a ICE Lite implementation, meaning that it will never initiate ICE connections but expect ICE Binding Requests on its open ports.

The remote media peer must be instructed about this. In the context of SDP this is achieved by signaling a=ice-lite in the remote SDP.

Dictionaries

TransportOptions

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

IceParameters

Field Type Description Required Default
usernameFragment String ICE username fragment. No  
password String ICE password. No  

IceCandidate

Field Type Description Required Default
foundation String Unique identifier that allows ICE to correlate candidates that appear on multiple transports. Yes  
priority Integer The assigned priority of the candidate. Yes  
ip String The IP address of the candidate. Yes  
protocol String The protocol of the candidate (“udp” / “tcp”). Yes  
port Integer The port for the candidate. Yes  
type String The type of candidate (always “host”). Yes  
tcpType String The type of TCP candidate (always “passive”). No  

IceSelectedTuple

Field Type Description Required Default
localIP String Local IP of the tuple. Yes  
localPort Integer Local port of the tuple. Yes  
remoteIP String Remote IP of the tuple. Yes  
remotePort Integer Remote port of the tuple. Yes  
protocol String The protocol of the tuple (“udp” / “tcp”). Yes  

LocalDtlsParameters

Field Type Description Required Default
role DtlsRole Local DTLS role. No “auto”
fingerprints LocalDtlsFingerprints Local DTLS fingerprints. Yes  

LocalDtlsFingerprints

Map of DTLS algorithms (as defined in the “Hash function Textual Names” registry initially specified in RFC 4572 Section 8) and their corresponding certificate fingerprint values (in lowercase hex string as expressed utilizing the syntax of “fingerprint” in RFC 4572 Section 5).

Field Type Description Required Default
sha-1 String SHA-1 certificate fingerprint. Yes  
sha-224 String SHA-224 certificate fingerprint. Yes  
sha-256 String SHA-256 certificate fingerprint. Yes  
sha-384 String SHA-384 certificate fingerprint. Yes  
sha-512 String SHA-512 certificate fingerprint. Yes  

RemoteDtlsParameters

Field Type Description Required Default
role DtlsRole Remote DTLS role. No “auto”
fingerprint RemoteDtlsFingerprint Remote DTLS fingerprint. Yes  

RemoteDtlsFingerprint

Field Type Description Required Default
algorithm String Hash function algorithm (“sha-1” / “sha-224” / “sha-256” / “sha-384” / “sha-512”). Yes  
value String Certificate fingerprint in lowercase hex. Yes  

Enums

IceState

Value Description
“new” No ICE Binding Requests have been received yet.
“connected” Valid ICE Binding Request have been received, but none with USE-CANDIDATE attribute. Outgoing media is allowed.
“completed” ICE Binding Request with USE_CANDIDATE attribute has been received. Media in both directions is now allowed.
“disconnected” ICE was “connected” or “completed” but it has suddenly failed (currently this can just happen if the selected tuple has “tcp” protocol).
“closed” ICE state when the transport has been closed.

DtlsRole

Value Description
“auto” The DTLS role is determined based on the resolved ICE role (the “controlled” role acts as DTLS client, the “controlling” role acts as DTLS server”). Since mediasoup is a ICE Lite implementation it always behaves as ICE “controlled”.
“client” DTLS client role. mediasoup transitions to DTLS client when transport.setRemoteDtlsParameters() is called with role “server” or “auto”.
“server” DTLS server role. mediasoup transitions to DTLS server when transport.setRemoteDtlsParameters() is called with “client” role.

DtlsState

Value Description
“new” DTLS procedures not yet initiated.
“connecting” DTLS connecting.
“connected” DTLS successfully connected (SRTP keys already extracted).
“failed” DTLS connection failed.
“closed” DTLS 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.iceRole

  • Read only

String indicating the ICE role of the transport. Due to the ICE Lite design, this is always “controlled”.

transport.iceLocalParameters

  • Read only

Local IceParameters of the transport.

transport.iceLocalCandidates

  • Read only

Sequence of local IceCandidate Objects associated to this transport.

transport.iceState

  • Read only

The current IceState of the transport.

transport.iceSelectedTuple

  • Read only

The selected IceSelectedTuple indicating information about the selected ICE candidate pair.

It is undefined if ICE is not yet established (no working candidate pair was found).

transport.dtlsLocalParameters

  • Read only

LocalDtlsParameters of the transport.

transport.dtlsState

  • Read only

The current DtlsState of the transport.

transport.dtlsRemoteCert

  • Read only

The remote certificate in PEM format (String). It is set once dtlsState becomes “connected”.

The application may want to inspect the remote certificate for authorization purposes by using some certificates utility such as the Node pem module.

Methods

transport.close()

Closes the transport and triggers a close event.

transport.dump()

For debugging purposes. Returns a Promise that resolves to an Object containing the transport internals.

transport.setRemoteDtlsParameters(parameters)

Set remote DTLS parameters. Returns a Promise that resolves to this transport. If something goes wrong the Promise is rejected with the corresponding Error object.

Argument Type Description Required Default
options RemoteDtlsParameters Remote DTLS parameters. Yes  

Usage example:

transport.setRemoteDtlsParameters({
    role        : "server",
    fingerprint : {
      algorithm : "sha-1",
      value     : "751b8193b7ed277e42bed6c48ef7043a49ce3faa"
    }
  })
  .then((transport) => {
    console.log("remote DTLS parameters set");
  })
  .catch((error) => {
    console.error("remote DTLS parameters failed: %o", error);
  });

transport.setMaxBitrate(bitrate)

Set maximum bitrate for media streams sent by the remote endpoint over this transport. Returns a Promise that resolves to this transport. If something goes wrong the Promise is rejected with the corresponding Error object.

Argument Type Description Required Default
bitrate Number Maximum sending bitrate in bps. Yes 0 (no limit)

Usage example:

transport.setMaxBitrate(250000);

transport.changeUfragPwd()

Set new local ICE usernameFragment and password. Useufl to produce a ICE restart. Returns a Promise that resolves to this transport. If something goes wrong the Promise is rejected with the corresponding Error object.

Events

The Transport class inherits from EventEmitter.

transport.on(“close”, fn(error))

Emitted when the transport is closed. In case of error, the callback is called with the corresponding Error object.

transport.on(“iceselectedtuplechange”, fn(iceSelectedTuple))

Emitted when the ICE selected tuple changes.

Argument Type Description
iceSelectedTuple IceSelectedTuple The new ICE selected tuple.

transport.on(“icestatechange”, fn(iceState))

Emitted when the ICE state changes.

Argument Type Description
iceState IceState The new ICE state.

transport.on(“dtlsstatechange”, fn(dtlsState))

Emitted when the DTLS state changes.

Argument Type Description
dtlsState DtlsState The new DTLS state.

RtpReceiver

A rtpReceiver describes a media stream (track) of audio or video sent by a remote media endpoint and received by the corresponding Peer instance in mediasoup.

The RtpReceiver instance is created by means of peer.RtpReceiver().

In the context of WebRTC 1.0, a RTCPeerConnection calling addStream() with an audio+video MediaStream will require two rtpReceivers in its associated Peer instance in mediasoup.

Dictionaries

RtpObject

Field Type Description Required Default
payloadType Integer RTP payload type. Yes  
marker Boolean RTP marker field. Yes  
sequenceNumber Integer RTP sequence number. Yes  
timestamp Integer RTP timestamp. Yes  
ssrc Integer RTP SSRC. Yes  
payload Buffer RTP binary payload. Yes  

Properties

rtpReceiver.id

  • Read only

Unique identifier (number).

rtpReceiver.closed

  • Read only

A Boolean indicating whether the rtpReceiver has been closed.

rtpReceiver.kind

  • Read only

The MediaKind handled by the rtpReceiver.

rtpReceiver.peer

  • Read only

The Peer instance owner of this rtpReceiver.

rtpReceiver.transport

  • Read only

The Transport assigned to this rtpReceiver.

rtpReceiver.rtpParameters

  • Read only

The effective RtpParameters of the rtpReceiver. It is filled once rtpReceiver.receive() is called and its Promise resolved.

Methods

rtpReceiver.close()

Closes the rtpReceiver and triggers a close event.

rtpReceiver.dump()

rtpReceiver.receive(rtpParameters)

Set remote RTP parameters. Returns a Promise that resolves to this rtpReceiver. If something goes wrong the Promise is rejected with the corresponding Error object.

Argument Type Description Required Default
rtpParameters RtpParameters Remote RTP parameters. Yes  

rtpReceiver.setTransport(transport)

Set a new Transport. Returns a Promise that resolves to this rtpReceiver. If something goes wrong the Promise is rejected with the corresponding Error object.

Argument Type Description Required Default
transport Transport New transport. Yes  

Events

The RtpReceiver class inherits from EventEmitter.

rtpReceiver.on(“close”, fn(error))

Emitted when the rtpReceiver is closed. In case of error, the callback is called with the corresponding Error object.

rtpReceiver.on(“parameters”, fn(rtpParameters))

Fired after calling receive() for the first time.

Argument Type Description
rtpParameters RtpParameters New effective RTP parameters.

rtpReceiver.on(“parameterschange”, fn(rtpParameters))

Fired after calling receive() with new RTP parameters.

Argument Type Description
rtpParameters RtpParameters New effective RTP parameters.

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

Emitted when a transport is assigned via setTransport().

Argument Type Description
transport Transport New assigned transport.

rtpReceiver.on(“rtpraw”, fn(packet))

Emitted for each valid RTP packet received by this rtpReceiver.

Argument Type Description
packet Buffer Full RTP packet in binary/raw format.

rtpReceiver.on(“rtpobject”, fn(packet))

Emitted for each valid RTP packet received by this rtpReceiver.

Argument Type Description
packet RtpObject Parsed RTP packet.

RtpSender

A rtpSender describes a media stream (track) of audio or video to be sent to a remote media endpoint by the corresponding Peer instance in mediasoup.

A RtpSender instance is created within the newrtpsender event.

Properties

rtpSender.id

  • Read only

Unique identifier (number).

rtpSender.closed

  • Read only

A Boolean indicating whether the rtpSender has been closed. This happens when the associated rtpReceiver has been closed.

rtpSender.kind

  • Read only

The MediaKind handled by the rtpSender.

rtpSender.peer

  • Read only

The Peer instance owner of this rtpSender.

rtpSender.transport

  • Read only

The Transport associated to the rtpSender.

rtpSender.rtpParameters

  • Read only

The RtpParameters of the rtpSender. These parameters are a subset of the parameters in the corresponding rtpReceiver (limited by the capabilities of this peer).

rtpSender.associatedRtpReceiver

  • Read only

The associated RtpReceiver instance.

rtpSender.active

  • Read only

Boolean indicating whether the remote endpoint associated to this rtpSender is capable of receiving the associated audio/video stream.

If the capabilities of the peer do not support the codecs required by this rtpSender, or the app called disable() or did not set a transportfor this rtpSender, the active property becomes false.

Methods

rtpSender.dump()

For debugging purposes. Returns a Promise that resolves to an Object containing the rtpSender internals.

rtpSender.disable(options)

The rtpSender stops sending RTP to the remote endpoint. It may trigger an activechange event (unless options.emit is set to false).

options is an optional object with the following fields:

Argument Type Description Required Default
emit Boolean Whether activechange event could be fired or not. No true

rtpSender.enable(options)

The rtpSender resumes sending RTP to the remote endpoint. It may trigger an activechange event (unless options.emit is set to false).

It has no effect if disable() was not called before.

options is an optional object with the following fields:

Argument Type Description Required Default
emit Boolean Whether activechange event could be fired or not. No true

Events

The RtpSender class inherits from EventEmitter.

rtpSender.on(“close”, fn(error))

Emitted when the rtpSender is closed. In case of error, the callback is called with the corresponding Error object.

rtpSender.on(“parameterschange”, fn(rtpParameters, active))

Fired once the RTP parameters of this rtpSender change.

Argument Type Description
rtpParameters RtpParameters New effective RTP parameters.
active Boolean Updated active value.

rtpSender.on(“activechange”, fn(active))

Fired when the active value changes.

Argument Type Description
active Boolean Updated active value.

RTP Dictionaries

Dictionaries

RtpCapabilities

Used by Peer.

Field Type Description Required Default
codecs sequence<RtpCodecParameters> The list of supported codecs. Yes  
headerExtensions sequence<RtpHeaderExtension> Supported RTP header extensions. No  
fecMechanisms sequence Supported Forward Error Correction (FEC) mechanisms and combinations. No  

RtpParameters

Used by RtpReceiver and RtpSender.

Field Type Description Required Default
muxId String Stable identifier associated to the RTP stream that corresponds to the MID RTP header extension defined in BUNDLE. No  
codecs sequence<RtpCodecParameters> The list of codecs to send or receive. Yes  
encodings sequence<RtpEncodingParameters> The “encodings” or “layers” to be used for simulcast, Scalable Video Coding, RTX, FEC, etc. No  
headerExtensions sequence<RtpHeaderExtensionParameters> Configured RTP header extensions. No  
rtcp RtcpParameters RTCP parameters. No  
userParameters Dictionary Custom user parameters. No  

userParameters are custom parameters set by the user in rtpReceiver.receive() and copied verbatim into the corresponding RtpParameters of all the associated RtpSender instances.

RtpCodecParameters

Field Type Description Required Default
kind MediaKind Media kind. Required for RtpCapabilities of Peer and RoomMediaCodec of Room  
name String The codec MIME type. Valid values are listed in IANA-RTP-2. The syntax must match type/subtype (examples: “audio/opus”, “video/H264”). Yes  
payloadType Integer The value that goes in the RTP Payload Type Field. Must be unique. Yes  
clockRate Integer Codec clock rate expressed in Hertz. Yes  
maxptime Integer The maximum packetization time. No  
ptime Integer The duration of media represented by a packet in millisecond. No  
numChannels Integer The number of channels (mono=1, stereo=2) for audio codecs. No 1
rtcpFeedback sequence<RtcpFeedback> Transport layer and codec-specific feedback messages for this codec. No  
parameters Dictionary Codec-specific parameters available for signaling. No  

RtcpFeedback

Field Type Description Required Default
type String “RTCP Feedback” Attribute Values (“ack”, “ccm”, “nack”, “goog-remb”, “transport-cc”, etc.). Yes  
parameter String For a type of “ack” or “nack”, valid values are the “ack” and “nack” Attribute Values enumerated in IANA-SDP-15 (“sli”, “rpsi”, etc.). For the Generic NACK feedback message defined in RFC 4585, the type attribute is set to “nack” and the parameter attribute is unset. For a type of “ccm”, valid values for parameter are the “Codec Control Messages” enumerated in IANA-SDP-19 (“fir”, “tmmbr” (includes “tmmbn”), etc.). No  

RtpEncodingParameters

Field Type Description Required Default
ssrc Integer The SSRC for this layering/encoding. No  
codecPayloadType Integer For per-encoding codec specifications. If set, it must point to an entry in codecs with same payloadType. No  
fec RtpFecParameters If set, specifies the FEC mechanism to use. No  
rtx RtpRtxParameters If set, specifies the RTX parameters. No  
resolutionScale Double Just for video streams. It signals how the video's resolution will be scaled down in each dimension. For example, if the value is 2.0, the video will be scaled down by a factor of 2 in each dimension, resulting in sending a video of one quarter size. For scalable video coding, it refers to the aggregate scale down of this layer when combined with all dependent layers. No 1.0
framerateScale Double Inverse of the input framerate fraction to be encoded. Example: 1.0 = full framerate, 2.0 = one half of the full framerate. For scalable video coding, it refers to the inverse of the aggregate fraction of input framerate achieved by this layer when combined with all dependent layers. No 1.0
maxFramerate Integer The maximum framerate to use for this encoding. Not used for scalable video coding. No  
active Boolean Whether this encoding is actively being sent/received. No true
encodingId String An identifier for the encoding object. Should be unique. Values must be composed only of case-sensitive alphanumeric characters (a-z, A-Z, 0-9) up to a maximum of 16 characters. Will be placed into the RID header extension. No  
dependencyEncodingIds sequence The encodingId values on which this layer depends. No  

RtpFecParameters

Field Type Description Required Default
mechanism String The Forward Error Correction (FEC) mechanism to use: “red”, “red+ulpfec” or “flexfec”. Yes  
ssrc Integer The SSRC to use for FEC. No  

RtpRtxParameters

Field Type Description Required Default
ssrc Integer The SSRC to use for retransmission. No  

RtpHeaderExtension

Used in RtpCapabilities.

Field Type Description Required Default
kind MediaKind Media kind. If unset applies to all. No.  
uri String The URI of the RTP header extension. Yes  
preferredId Integer The value that goes in the RTP packet. Yes  
preferredEncrypt Boolean If true, the value in the header is encrypted as per RFC 6904. No false

RtpHeaderExtensionParameters

Used in RtpParameters.

Field Type Description Required Default
uri String The URI of the RTP header extension. Yes  
id Integer The value that goes in the RTP packet. Yes  
encrypt Boolean If true, the value in the header is encrypted as per RFC 6904. No false
parameters Dictionary Configuration parameters for the header extension. An example is the “vad” attribute in the client-to-mixer header extension. No  

RtcpParameters

Field Type Description Required Default
cname String The Canonical Name (CNAME) used by RTCP (e.g. in SDES messages). No  
ssrc Integer The SSRC to be used in the “SSRC of packet sender” field defined in RFC 3550 Section 6.4.2 (Receiver Report) and RFC 4585 Section 6.1 (Feedback Messages), as well as the “SSRC” field defined in RFC 3611 Section 2 (Extended Reports). No  
reducedSize Boolean Whether reduced size RTCP RFC 5506 is configured (if true) or compound RTCP as specified in RFC 3550 (if false). No false

Enums

MediaKind

Value Description
“audio” Audio kind.
“video” Video kind.
“depth” Depth kind.

errors

The errors module (exported via mediasoup.errors) holds custom Error classes internally used by mediasoup.

Classes

errors.InvalidStateError

This error happens when an API method is called on an Object in invalid state (for example when such an Object is closed).

extra

The extra module (exported via mediasoup.extra) holds utilities for the application developer.

Functions

extra.fingerprintFromSDP(sdpFingerprint)

Generates a raw DTLS certificate fingerprint (lowercase hex string without colons).

Argument Type Description Required Default
sdpFingerprint String SDP fingerprint (uppercase hex string with colons). Yes  

Usage example:

const sdpFingerprint = "75:1B:81:93:B7:ED:27:7E:42:BE:D6:C4:8E:F7:04:3A:49:CE:3F:EE";

extra.fingerprintFromSDP(sdpFingerprint);
// => "751b8193b7ed277e42bed6c48ef7043a49ce3fee"

extra.fingerprintToSDP(rawFingerprint)

Generates a DTLS certificate fingerprint for SDP usage (uppercase hex string with colons).

Argument Type Description Required Default
rawFingerprint String Raw fingerprint (lowercase hex string without colons). Yes  

Usage example:

const rawFingerprint = "751b8193b7ed277e42bed6c48ef7043a49ce3fee";

extra.fingerprintToSDP(rawFingerprint);
// => "75:1B:81:93:B7:ED:27:7E:42:BE:D6:C4:8E:F7:04:3A:49:CE:3F:EE"

extra.paramFromSDP(param)

Generates a mediasoup normalized parameter name (camelcase).

Argument Type Description Required Default
param String SDP parameter name. Yes  

Usage example:

extra.paramFromSDP("profile-level-id");
// => "profileLevelId"

extra.paramToSDP(param)

Generates a SDP normalized parameter name (lowercase separated by “-“).

Argument Type Description Required Default
param String mediasoup parameter name. Yes  

Usage example:

extra.paramToSDP("packetizationMode");
// => "packetization-mode"

webrtc

The webrtc module (exported via mediasoup.webrtc) exposes a high-level API matching a subset of the W3C WebRTC 1.0 API. It includes the following classes:

Usage example:

const mediasoup = require("mediasoup");
const RTCPeerConnection = mediasoup.webrtc.RTCPeerConnection;
// This is supposed to be our application signaling stack (up to you):
const signaling = require("./signaling");

// Create a mediasoup Server.
const mediaServer = mediasoup.Server({
  logLevel   : "debug",
  rtcIPv4    : true,
  rtcIPv6    : false,
  rtcMinPort : 40000,
  rtcMaxPort : 49999
});

// Room options.
const roomOptions = {
  mediaCodecs : [
    {
      kind        : "audio",
      name        : "audio/opus",
      clockRate   : 48000,
      payloadType : 100
    },
    {
      kind        : "video",
      name        : "video/vp8",
      clockRate   : 90000,
      payloadType : 123
    }
  ]
};

// Somehow our app decides to create a room by providing an "appRoom" (which
// is up to the application).
signaling.on("createroom", (appRoom) => {
  mediaServer.createRoom(roomOptions)
    .then((mediaRoom) => {
      handleRoom(appRoom, mediaRoom);
    });
});

function handleRoom(appRoom, mediaRoom) {
  // Handle new participants in the room. Our custom signaling application
  // fires a "join" event when a new participant wishes to join a room (this is
  // up to the application) by providing some data:
  // - `participant` is supposed to be a JSON with info about the participant:
  //   - `username`: An unique username.
  //   - `usePlanB`: Whether it's a Chrome based endpoint.
  //   - `capabilities`: An SDP created by the browser.
  // - `request` is supposed to be a WebSocket or HTTP request that we must
  //   accept or reject (if something is wrong).
  appRoom.on("join", (participant, request) => {
    handleParticipant(participant, request, appRoom, mediaRoom);
  });
}

function handleParticipant(participant, request, appRoom, mediaRoom) {
  // Create a new mediasoup Peer within the mediasoup Room and create a
  // RTCPeerConnection for it.
  let mediaPeer = mediaRoom.Peer(participant.username);
  let peerconnection = new RTCPeerConnection({
    peer     : mediaPeer,
    usePlanB : participant.usePlanB
  });

  // Participant is required to join the mediasoup Room by providing a
  // capabilities SDP.
  peerconnection.setCapabilities(participant.capabilities)
    // OK, so accept the request.
    .then(() => {
      request.accept();

      // And then generate the initial SDP offer for this participant and send
      // it to him.
      sendSdpOffer(participant, peerconnection, appRoom);
    })
    // Something was wrong, reject the request.
    .catch((error) => {
      request.reject(error);

      // And also close the RTCPeerConnection.
      peerconnection.close();
    });

  // When something changes in the mediasoup Room (such as when a new participant
  // joins or a participant leaves) provides this participant with an
  // updated SDP re-offer.
  peerconnection.on("negotiationneeded", () => {
    sendSdpOffer(participant, peerconnection, appRoom);
  });

  // If the participant leaves the room (by means of the custom signaling
  // mechanism up to the application) close its associated peerconnection.
  participant.on('leave', () => {
    peerconnection.close();
  });
}

function sendSdpOffer(participant, peerconnection, appRoom) {
  // Create an SDP offer for this participant.
  peerconnection.createOffer({
    offerToReceiveAudio : 1,
    offerToReceiveVideo : 1
  })
  // Set it as local description.
  .then((desc) => {
    return peerconnection.setLocalDescription(desc);
  })
  // Send the SDP offer to the browser.
  .then(() => {
    return participant.send({
      offer : peerconnection.localDescription.serialize()
    });
  })
  // Upon receipt of the response from the browser, take the SDP answer and
  // set it as remote description.
  .then((data) => {
    return peerconnection.setRemoteDescription(data.answer);
  })
  // If something goes wrong, reset the RTCPeerConnection internal status so,
  // at least, things may work later in a new re-offer.
  .catch((error) => {
    peerconnection.reset();
  });
}

Check the WebRTC API tricks section to get help regarding how to signal the relationship between audio/video streams and their associated room participants.

webrtc.RTCPeerConnection

Internally, a peerconnection manages a given Peer instance and all its associated Transport, RtpReceiver and RtpSender instances.

Dictionaries

RTCPeerConnectionOptions

Field Type Description Required Default
peer Peer A mediasoup Peer instance. Yes  
transportOptions TransportOptions Options for the transport. No  
usePlanB Boolean Expect and generate Plan B SDPs for this peerconnection. No false
maxBitrate Number Maximum sending bitrate in bps (see transport.setMaxBitrate()). No 0 (no limit)

Chrome/Chromium browser does not yet implement Unified Plan (see open issue) and, hence, setting usePlanB to true is required for Chrome/Chromium based endpoints.

In the other side, latest versions of Firefox do implement “Unified Plan”, so usePlanB must be false (or unset) for endpoints running Firefox.

RTCOfferOptions

Field Type Description Required Default
offerToReceiveAudio Integer Number of audio tracks the remote peer is allowed to send. No 1
offerToReceiveVideo Integer Number of video tracks the remote peer is allowed to send. No 1

These options are just valid for the initial SDP offer sent to the endpoint.

Enums

RTCSignalingState

Value Description
“stable” There is no offer­answer exchange in progress. This is also the initial state in which case the local and remote descriptions are empty.
“have-local-offer” A local description, of type “offer”, has been successfully applied.
“have-remote-offer” A remote description, of type “offer”, has been successfully applied.

Constructor

new webrtc.RTCPeerConnection(room, peerName, options)

Argument Type Description Required Default
options RTCPeerConnectionOptions RTCPeerConnection options. Yes  

Properties

peerconnection.closed

  • Read only

A Boolean indicating whether the peerconnection (so its associated peer) has been closed.

peerconnection.peer

  • Read only

Retrieves the Peer instance associated to this peerconnection.

peerconnection.localDescription

  • Read only

Gets the local RTCSessionDescription.

peerconnection.remoteDescription

  • Read only

Gets the remote RTCSessionDescription (if any).

peerconnection.signalingState

  • Read only

The RTCSignalingState of this peerconnection.

Methods

peerconnection.close()

Closes the peerconnection and triggers a close event.

peerconnection.setCapabilities(sdp)

The endpoint must provide its media capabilities in order to join a room. To do that, the endpoint must create a RTCPeerConnection, call createOffer({ offerToReceiveAudio: 1, offerToReceiveVideo: 1 }) on it, obtain the desc.sdp and send it to mediasoup.

Argument Type Description Required Default
sdp String An SDP providing the media capabilities of the peer. Yes  

In order to get the capabilities SDP in the WebRTC browser/endpoint, just call pc.createOffer() (as stated above) but DO NOT call pc.setLocalDescription()).

peerconnection.createOffer(options)

Generates a blob of SDP that contains an RFC 3264 offer with the supported configurations for the session, including descriptions of the internal Transport, RtpReceiver and RtpSender instances attached to this peerconnection, the RTP parameters supported by both the room and the remote endpoint, and local ICE candidates.

Returns a Promise that resolves to a local RTCSessionDescription instance of type “offer”.

Argument Type Description Required Default
options RTCOfferOptions Options for the offer. No  

peerconnection.createAnswer()

Generates a blob of SDP that contains an RFC 3264 answer.

Returns a Promise that resolves to a local RTCSessionDescription instance of type “answer”.

peerconnection.setLocalDescription(desc)

Instructs the peerconnection to apply the supplied RTCSessionDescription as the local offer or answer.

Returns a Promise.

Argument Type Description Required Default
desc RTCSessionDescription Local description. Yes  

peerconnection.setRemoteDescription(desc)

Instructs the peerconnection to apply the supplied RTCSessionDescription as the remote offer or answer.

Returns a Promise.

Argument Type Description Required Default
desc RTCSessionDescription Remote description. Yes  

The mediasoup implementation of RTCPeerConnection requires that the SDP O/A procedure is always initiated my mediasoup. This means that setRemoteDescription() can only be called with a remote answer. To be clear: the remote endpoint should not attempt to renegotiate by sending a SDP re-offer.

If the remote endpoint wishes to add/remove a sending audio or video track, it must signal such a desire to the server application (by means of the signaling protocol up to the application) so the server side application can provide him with a re-offer (by calling createOffer() and setLocalDescription()). The remote endpoint can then produce an SDP answer containing the desired changes (sending audio/video addition or removal, etc).

peerconnection.reset()

Reset the internal machinery of the RTCPeerConnection. It basically sets the signalingState to “stable”.

Useful if the app failed to receive a pending SDP re-answer from the client.

peerconnection.restartIce()

By calling this method, a SDP re-offer is triggered with new a=ice-ufrag and a=ice-pwd values, producing a “ICE restart” in the browser.

Returns a Promise.

Events

The RTCPeerConnection class inherits from EventEmitter.

peerconnection.on(“close”, fn(error))

Emitted when the peerconnection is closed. In case of error, the callback is called with the corresponding Error object.

peerconnection.on(“signalingstatechange”, fn())

Emitted when the signalingState of the peerconnection changes.

peerconnection.on(“negotiationneeded”, fn())

Emitted when the room changes (a new peer joins it, a peer leaves it, or an existing peer modifies its sending media description).

When “negotiationneeded” is fired on a peerconnection, the application should retrieve its updated local RTCSessionDescription (by means of createOffer() and setLocalDescription()) and send it to the associated endpoint.

webrtc.RTCSessionDescription

Dictionaries

RTCSessionDescriptionInit

Field Type Description Required Default
type RTCSdpType SDP type. Yes  
sdp String SDP body. Yes  

Enums

RTCSdpType

Value Description
“offer” SDP offer.
“answer” SDP answer.

Constructor

new webrtc.RTCSessionDescription(descriptionInitDict)

Argument Type Description Required Default
descriptionInitDict RTCSessionDescriptionInit Initialization data. Yes  

Properties

description.type

The RTCSdpType type.

description.sdp

The SDP body (String).

Methods

description.serialize()

Returns an object with two keys: type and sdp.