WebRTC: Real-Time Communication in Browsers

W3C Recommendation

More details about this document
This version:
https://www.w3.org/TR/2024/REC-webrtc-20241008/
Latest published version:
https://www.w3.org/TR/webrtc/
Latest editor's draft:
https://w3c.github.io/webrtc-pc/
History:
https://www.w3.org/standards/history/webrtc/
Commit history
Test suite:
https://github.com/web-platform-tests/wpt/tree/master/webrtc/
Implementation report:
https://w3c.github.io/webrtc-interop-reports/webrtc-pc-report.html
Editors:
Cullen Jennings (Cisco)
Florent Castelli (Google)
Henrik Boström (Google)
Jan-Ivar Bruaroey (Mozilla)
Former editors:
Adam Bergkvist (Ericsson) - Until
Daniel C. Burnett (Invited Expert) - Until
Anant Narayanan (Mozilla) - Until
Bernard Aboba (Microsoft Corporation) - Until
Taylor Brandstetter (Google) - Until
Feedback:
GitHub w3c/webrtc-pc (pull requests, new issue, open issues)
public-webrtc@w3.org with subject line [webrtc] … message topic … (archives)
Participate
Mailing list

See also translations.


Abstract

This document defines a set of ECMAScript APIs in WebIDL to allow media and generic application data to be sent to and received from another browser or device implementing the appropriate set of real-time protocols. This specification is being developed in conjunction with a protocol specification developed by the IETF RTCWEB group and an API specification to get access to local media devices.

Status of This Document

This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

This document includes Proposed Amendments and Candidate Amendments to the current W3C Recommendation dated January 26, 2021.

Its associated test suite has been used to build an implementation report of the API at the time of its initial publication as a Recommendation. That test suite has been updated to integrate most of the amendments, and an updated implementation report focused on the implementation status of these amendments has been used to select features with double implementation as proposed amendments.

This document was published by the Web Real-Time Communications Working Group as a Recommendation using the Recommendation track. It includes proposed amendments, introducing substantive changes and new features since the previous Recommendation.

W3C recommends the wide deployment of this specification as a standard for the Web.

A W3C Recommendation is a specification that, after extensive consensus-building, is endorsed by W3C and its Members, and has commitments from Working Group members to royalty-free licensing for implementations. Future updates to this Recommendation may incorporate new features.

Candidate additions are marked in the document.

Candidate corrections are marked in the document.

Proposed additions are marked in the document.

Proposed corrections are marked in the document.

The W3C Membership and other interested parties are invited to review the proposed additions and send comments through 08 December 2024. Advisory Committee Representatives should consult their WBS questionnaires.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 03 November 2023 W3C Process Document.

1. Introduction

This section is non-normative.

There are a number of facets to peer-to-peer communications and video-conferencing in HTML covered by this specification:

This document defines the APIs used for these features. This specification is being developed in conjunction with a protocol specification developed by the IETF RTCWEB group and an API specification to get access to local media devices [GETUSERMEDIA] developed by the WebRTC Working Group. An overview of the system can be found in [RFC8825] and [RFC8826].

2. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words MAY, MUST, MUST NOT, and SHOULD in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.

This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.

Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)

Implementations that use ECMAScript to implement the APIs defined in this specification MUST implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL], as this specification uses that specification and terminology.

3. Terminology

The EventHandler interface, representing a callback used for event handlers, is defined in [HTML].

The concepts queue a task and networking task source are defined in [HTML].

The concept fire an event is defined in [DOM].

The terms event, event handlers and event handler event types are defined in [HTML].

Performance.timeOrigin and Performance.now() are defined in [hr-time].

The terms serializable objects, serialization steps, and deserialization steps are defined in [HTML].

The terms MediaStream, MediaStreamTrack, and MediaStreamConstraints are defined in [GETUSERMEDIA]. Note that MediaStream is extended in 9.2 MediaStream in this document while MediaStreamTrack is extended in 9.3 MediaStreamTrack in this document.

The term Blob is defined in [FILEAPI].

The term media description is defined in [RFC4566].

The term media transport is defined in [RFC7656].

The term generation is defined in [RFC8838] Section 2.

The terms stats object and monitored object are defined in [WEBRTC-STATS].

When referring to exceptions, the terms throw and created are defined in [WEBIDL].

The callback VoidFunction is defined in [WEBIDL].

The term "throw" is used as specified in [INFRA]: it terminates the current processing steps.

The terms fulfilled, rejected, resolved, and settled used in the context of Promises are defined in [ECMASCRIPT-6.0].

The AlgorithmIdentifier is defined in [WebCryptoAPI].

Note

The general principles for Javascript APIs apply, including the principle of run-to-completion and no-data-races as defined in [API-DESIGN-PRINCIPLES]. That is, while a task is running, external events do not influence what's visible to the Javascript application. For example, the amount of data buffered on a data channel will increase due to "send" calls while Javascript is executing, and the decrease due to packets being sent will be visible after a task checkpoint.
It is the responsibility of the user agent to make sure the set of values presented to the application is consistent - for instance that getContributingSources() (which is synchronous) returns values for all sources measured at the same time.

4. Peer-to-peer connections

4.1 Introduction

This section is non-normative.

An RTCPeerConnection instance allows an application to establish peer-to-peer communications with another RTCPeerConnection instance in another browser, or to another endpoint implementing the required protocols. Communications are coordinated by the exchange of control messages (called a signaling protocol) over a signaling channel which is provided by unspecified means, but generally by a script in the page via the server, e.g. using WebSocket or XMLHttpRequest.

4.2 Configuration

Proposed Correction 1:Set default values of the RTCConfiguration dictionary, aligning it with current implementations (PR #2691)
Proposed Correction 2:Allow an implementation-defined limited to the number of configured ICE Servers (PR #2679)

4.2.1 RTCConfiguration Dictionary

4.2.1 RTCConfiguration Dictionary

The RTCConfiguration defines a set of parameters to configure how the peer-to-peer communication established via RTCPeerConnection is established or re-established.

dictionary RTCConfiguration {
  sequence<RTCIceServer> iceServersiceServers = [];
  RTCIceTransportPolicy iceTransportPolicyiceTransportPolicy = "all";
  RTCBundlePolicy bundlePolicybundlePolicy = "balanced";
  RTCRtcpMuxPolicy rtcpMuxPolicyrtcpMuxPolicy = "require";
  sequence<RTCCertificate> certificatescertificates = [];
  [EnforceRange] octet iceCandidatePoolSize = 0;
};
Dictionary RTCConfiguration Members
Dictionary RTCConfiguration Members
iceServers of type sequence<RTCIceServer>, defaulting to [].

An array of objects describing servers available to be used by ICE, such as STUN and TURN servers. If the number of ICE servers exceeds an implementation-defined limit, ignore the ICE servers above the threshold. This implementation defined limit MUST be at least 32.

iceTransportPolicy of type RTCIceTransportPolicy, defaulting to "all".

Indicates which candidates the ICE Agent is allowed to use.

bundlePolicy of type RTCBundlePolicy, defaulting to "balanced".

Indicates which media-bundling policy to use when gathering ICE candidates.

rtcpMuxPolicy of type RTCRtcpMuxPolicy, defaulting to "require".

Indicates which rtcp-mux policy to use when gathering ICE candidates.

certificates of type sequence<RTCCertificate>, defaulting to [].

A set of certificates that the RTCPeerConnection uses to authenticate.

Valid values for this parameter are created through calls to the generateCertificate() function.

Although any given DTLS connection will use only one certificate, this attribute allows the caller to provide multiple certificates that support different algorithms. The final certificate will be selected based on the DTLS handshake, which establishes which certificates are allowed. The RTCPeerConnection implementation selects which of the certificates is used for a given connection; how certificates are selected is outside the scope of this specification.

Note

Existing implementations only utilize the first certificate provided; the others are ignored.

If this value is absent, then a default set of certificates is generated for each RTCPeerConnection instance.

This option allows applications to establish key continuity. An RTCCertificate can be persisted in [INDEXEDDB] and reused. Persistence and reuse also avoids the cost of key generation.

The value for this configuration option cannot change after its value is initially selected.

iceCandidatePoolSize of type octet, defaulting to 0

Size of the prefetched ICE pool as defined in [RFC8829RFC9429] (section 3.5.4. and section 4.1.1.).

Proposed Correction 17:Remove single-value RTCIceCredentialType enum (PR #2767)

4.2.2 RTCIceCredentialType Enum

enum RTCIceCredentialType {
  "password"
};
Enumeration description
password The credential is a long-term authentication username and password, as described in [RFC5389], Section 10.2.
Proposed Correction 17:Remove single-value RTCIceCredentialType enum (PR #2767)

4.2.3 RTCIceServer Dictionary

4.2.2 RTCIceServer Dictionary

The RTCIceServer dictionary is used to describe the STUN and TURN servers that can be used by the ICE Agent to establish a connection with a peer.

dictionary RTCIceServer {
  required (DOMString or sequence<DOMString>) urls;
  DOMString username;
  DOMString credential;
  RTCIceCredentialType credentialType = "password";
};
Dictionary RTCIceServer Members
Dictionary RTCIceServer Members
urls of type (DOMString or sequence<DOMString>), required

STUN or TURN URI(s) as defined in [RFC7064] and [RFC7065] or other URI types.

username of type DOMString

If this RTCIceServer object represents a TURN server, and credentialType is "password", then this attribute attribute specifies the username to use with with that TURN server.

credential of type DOMString

If this RTCIceServer object represents a TURN server, then this attribute specifies the credential to use with that TURN server.

If credentialType is "password", credential represents a long-term authentication authentication password, as as described in [RFC5389], Section 10.2.

Note

To support additional values of credentialType, credential may evolve in future as a union.

credentialType of type RTCIceCredentialType, defaulting to "password"

If this RTCIceServer object represents a TURN server, then this attribute specifies how credential should be used when that TURN server requests authorization.

An example array of RTCIceServer objects is:

[
  {urls: 'stun:stun1.example.net'},
  {urls: ['turns:turn.example.org', 'turn:turn.example.net'],
    username: 'user',
    credential: 'myPassword',
    credentialType: 'password'},
];

4.2.3 RTCIceTransportPolicy Enum

As described in [RFC9429] (section 4.1.1.), if the iceTransportPolicy member of the RTCConfiguration is specified, it defines the ICE candidate policy [RFC9429] (section 3.5.3.) the browser uses to surface the permitted candidates to the application; only these candidates will be used for connectivity checks.

WebIDLenum RTCIceTransportPolicy {
  "relay",
  "all"
};
RTCIceTransportPolicy Enumeration description
Enum valueDescription
relay

The ICE Agent uses only media relay candidates such as candidates passing through a TURN server.

Note
This can be used to prevent the remote endpoint from learning the user's IP addresses, which may be desired in certain use cases. For example, in a "call"-based application, the application may want to prevent an unknown caller from learning the callee's IP addresses until the callee has consented in some way.
all

The ICE Agent can use any type of candidate when this value is specified.

Note
The implementation can still use its own candidate filtering policy in order to limit the IP addresses exposed to the application, as noted in the description of RTCIceCandidate.address.

4.2.4 RTCBundlePolicy Enum

As described in [RFC9429] (section 4.1.1.), bundle policy affects which media tracks are negotiated if the remote endpoint is not bundle-aware, and what ICE candidates are gathered. If the remote endpoint is bundle-aware, all media tracks and data channels are bundled onto the same transport.

WebIDLenum RTCBundlePolicy {
  "balanced",
  "max-compat",
  "max-bundle"
};
RTCBundlePolicy Enumeration description
Enum valueDescription
balanced Gather ICE candidates for each media type in use (audio, video, and data). If the remote endpoint is not bundle-aware, negotiate only one audio and video track on separate transports.
max-compat Gather ICE candidates for each track. If the remote endpoint is not bundle-aware, negotiate all media tracks on separate transports.
max-bundle Gather ICE candidates for only one track. If the remote endpoint is not bundle-aware, negotiate only one media track.

4.2.5 RTCRtcpMuxPolicy Enum

As described in [RFC9429] (section 4.1.1.), the RTCRtcpMuxPolicy affects what ICE candidates are gathered to support non-multiplexed RTCP. The only value defined in this spec is "require".

WebIDLenum RTCRtcpMuxPolicy {
  "require"
};
RTCRtcpMuxPolicy Enumeration description
Enum valueDescription
require Gather ICE candidates only for RTP and multiplex RTCP on the RTP candidates. If the remote endpoint is not capable of rtcp-mux, session negotiation will fail.

4.2.6 Offer/Answer Options

These dictionaries describe the options that can be used to control the offer/answer creation process.

WebIDLdictionary RTCOfferAnswerOptions {};
Dictionary RTCOfferAnswerOptions Members
WebIDLdictionary RTCOfferOptions : RTCOfferAnswerOptions {
  boolean iceRestart = false;
};
Dictionary RTCOfferOptions Members
iceRestart of type boolean, defaulting to false

When the value of this dictionary member is true, or the relevant RTCPeerConnection object's [[LocalIceCredentialsToReplace]] slot is not empty, then the generated description will have ICE credentials that are different from the current credentials (as visible in the currentLocalDescription attribute's SDP). Applying the generated description will restart ICE, as described in section 9.1.1.1 of [RFC5245].

When the value of this dictionary member is false, and the relevant RTCPeerConnection object's [[LocalIceCredentialsToReplace]] slot is empty, and the currentLocalDescription attribute has valid ICE credentials, then the generated description will have the same ICE credentials as the current value from the currentLocalDescription attribute.

Note

Performing an ICE restart is recommended when iceConnectionState transitions to "failed". An application may additionally choose to listen for the iceConnectionState transition to "disconnected" and then use other sources of information (such as using getStats to measure if the number of bytes sent or received over the next couple of seconds increases) to determine whether an ICE restart is advisable.

The RTCAnswerOptions dictionary describe options specific to session description of type "answer" (none in this version of the specification).

WebIDLdictionary RTCAnswerOptions : RTCOfferAnswerOptions {};

4.3 State Definitions

4.3.1 RTCSignalingState Enum

WebIDLenum RTCSignalingState {
  "stable",
  "have-local-offer",
  "have-remote-offer",
  "have-local-pranswer",
  "have-remote-pranswer",
  "closed"
};
RTCSignalingState Enumeration description
Enum valueDescription
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.
have-local-pranswer A remote description of type "offer" has been successfully applied and a local description of type "pranswer" has been successfully applied.
have-remote-pranswer A local description of type "offer" has been successfully applied and a remote description of type "pranswer" has been successfully applied.
closed The RTCPeerConnection has been closed; its [[IsClosed]] slot is true.
signaling state transition diagram
Figure 1 Non-normative signaling state transitions diagram. Method calls abbreviated.

An example set of transitions might be:

Caller transition:
Callee transition:

4.3.2 RTCIceGatheringState Enum

WebIDLenum RTCIceGatheringState {
  "new",
  "gathering",
  "complete"
};
RTCIceGatheringState Enumeration description
Enum valueDescription
new Any of the RTCIceTransports are in the "new" gathering state and none of the transports are in the "gathering" state, or there are no transports.
gathering Any of the RTCIceTransports are in the "gathering" state.
complete At least one RTCIceTransport exists, and all RTCIceTransports are in the "complete" gathering state.
Proposed Correction 3:Update RTCIceGatheringState to clarify the relevant transport it represents (PR #2680)

The set of transports considered is the set of transports one presently referenced by the PeerConnection's RTCPeerConnection's set of transceivers and the RTCPeerConnection's [[SctpTransport]] internal slot if not null.

4.3.3 RTCPeerConnectionState Enum

WebIDLenum RTCPeerConnectionState {
  "closed",
  "failed",
  "disconnected",
  "new",
  "connecting",
  "connected"
};
Proposed Correction 3:Update RTCPeerConnectionState to clarify the relevant transport it represents (PR #2680)
Proposed Correction 4:Ensure the connecting state happens whenever a ICE or DTLS transport is new (PR #2687)
RTCPeerConnectionState Enumeration description
Enumeration description
Enum valueDescription
closed The RTCPeerConnection object's [[IsClosed]] slot is true.
closed [[IceConnectionState]] is "closed".
failed The previous state doesn't apply apply, and any RTCIceTransports are in the either [[IceConnectionState]] is "failed" state or any RTCDtlsTransports are in the "failed" state.
disconnected None of the previous states apply and any RTCIceTransports are in the apply, and [[IceConnectionState]] is "disconnected" state".
new None of the previous states apply apply, and all RTCIceTransports are in the either [[IceConnectionState]] is "new" or "closed" state, and all RTCDtlsTransports are in the "new" or "closed" state, or there are no transports.
connecting None of the previous states apply and any RTCIceTransport is in the "checking" state or any RTCDtlsTransport is in the "connecting" state.
connected None of the previous states apply and all RTCIceTransports are in the "connected"apply, [[IceConnectionState]] is "completed" or connected"closed" state, and all RTCDtlsTransports are in the "connected" or "closed" state.
connecting None of the previous states apply.
Note

In the "connecting" state, one or more RTCIceTransports are in the "new" or "checking" state, or one or more RTCDtlsTransports are in the "new" or "connecting" state.

The set of transports considered is the set of transports one presently referenced by the PeerConnection's RTCPeerConnection's set of transceivers and the RTCPeerConnection's [[SctpTransport]] internal slot if not null.

4.3.4 RTCIceConnectionState Enum

WebIDLenum RTCIceConnectionState {
  "closed",
  "failed",
  "disconnected",
  "new",
  "checking",
  "completed",
  "connected"
};
RTCIceConnectionState Enumeration description
Enum valueDescription
closed The RTCPeerConnection object's [[IsClosed]] slot is true.
failed The previous state doesn't apply and any RTCIceTransports are in the "failed" state.
disconnected None of the previous states apply and any RTCIceTransports are in the "disconnected" state.
new None of the previous states apply and all RTCIceTransports are in the "new" or "closed" state, or there are no transports.
checking None of the previous states apply and any RTCIceTransports are in the "new" or "checking" state.
completed None of the previous states apply and all RTCIceTransports are in the "completed" or "closed" state.
connected None of the previous states apply and all RTCIceTransports are in the "connected", "completed" or "closed" state.
Proposed Correction 3:Update RTCIceConnectionState to clarify the relevant transport it represents (PR #2680)

The set of transports considered is the set of transports one presently referenced by the PeerConnection's RTCPeerConnection's set of transceivers and the RTCPeerConnection's [[SctpTransport]] internal slot if not null.

Note that if an RTCIceTransport is discarded as a result of signaling (e.g. RTCP mux or bundling), or created as a result of signaling (e.g. adding a new media description), the state may advance directly from one state to another.

4.4 RTCPeerConnection Interface

The [RFC9429] specification, as a whole, describes the details of how the RTCPeerConnection operates. References to specific subsections of [RFC9429] are provided as appropriate.

4.4.1 Operation

Calling new RTCPeerConnection(configuration) creates an RTCPeerConnection object.

configuration.iceServers contains information used to find and access the servers used by ICE. The application can supply multiple servers of each type, and any TURN server MAY also be used as a STUN server for the purposes of gathering server reflexive candidates.

An RTCPeerConnection object has a [[SignalingState]], and the aggregated states [[ConnectionState]], [[IceGatheringState]], and [[IceConnectionState]]. These are initialized when the object is created.

The ICE protocol implementation of an RTCPeerConnection is represented by an ICE agent [RFC5245]. Certain RTCPeerConnection methods involve interactions with the ICE Agent, namely addIceCandidate, setConfiguration, setLocalDescription, setRemoteDescription and close. These interactions are described in the relevant sections in this document and in [RFC9429]. The ICE Agent also provides indications to the user agent when the state of its internal representation of an RTCIceTransport changes, as described in 5.6 RTCIceTransport Interface.

The task source for the tasks listed in this section is the networking task source.

Note

The state of the SDP negotiation is represented by the internal variables [[SignalingState]], [[CurrentLocalDescription]], [[CurrentRemoteDescription]], [[PendingLocalDescription]] and [[PendingRemoteDescription]]. These are only set inside the setLocalDescription and setRemoteDescription operations, and modified by the addIceCandidate operation and the surface a candidate procedure. In each case, all the modifications to all the five variables are completed before the procedures fire any events or invoke any callbacks, so the modifications are made visible at a single point in time.

As one of the unloading document cleanup steps, run the following steps:

  1. Let window be document's relevant global object.

  2. For each RTCPeerConnection object connection whose relevant global object is window, close the connection with connection and the value true.

4.4.1.1 Constructor

When the RTCPeerConnection.constructor() is invoked, the user agent MUST run the following steps:

  1. If any of the steps enumerated below fails for a reason not specified here, throw an UnknownError with the message attribute set to an appropriate description.

  2. Let connection be a newly created RTCPeerConnection object.

  3. Let connection have a [[DocumentOrigin]] internal slot, initialized to the relevant settings object's origin.

  4. Let configuration be the method's first argument.
  5. If the certificates value in configuration is non-empty, run the following steps for each certificate in certificates:

    1. If the value of certificate.expires is less than the current time, throw an InvalidAccessError.

    2. If certificate.[[Origin]] is not same origin with connection.[[DocumentOrigin]], throw an InvalidAccessError.

    3. Store certificate.

  6. Else, generate one or more new RTCCertificate instances with this RTCPeerConnection instance and store them. This MAY happen asynchronously and the value of certificates remains undefined for the subsequent steps. As noted in Section 4.3.2.3 of [RFC8826], WebRTC utilizes self-signed rather than Public Key Infrastructure (PKI) certificates, so that the expiration check is to ensure that keys are not used indefinitely and additional certificate checks are unnecessary.

  7. Initialize connection's ICE Agent.

  8. Let connection have a [[Configuration]] internal slot, initialized to null. Set the configuration specified by configuration.

  9. Let connection have an [[IsClosed]] internal slot, initialized to false.

  10. Let connection have a [[NegotiationNeeded]] internal slot, initialized to false.

  11. Let connection have an [[SctpTransport]] internal slot, initialized to null.

  12. Let connection have a [[DataChannels]] internal slot, initialized to an empty ordered set.

  13. Let connection have an [[Operations]] internal slot, representing an operations chain, initialized to an empty list.

  14. Let connection have a [[UpdateNegotiationNeededFlagOnEmptyChain]] internal slot, initialized to false.

  15. Let connection have an [[LastCreatedOffer]] internal slot, initialized to "".

  16. Let connection have an [[LastCreatedAnswer]] internal slot, initialized to "".

  17. Let connection have an [[EarlyCandidates]] internal slot, initialized to an empty list.

  18. Let connection have an [[SignalingState]] internal slot, initialized to "stable".

  19. Let connection have an [[IceConnectionState]] internal slot, initialized to "new".

  20. Let connection have an [[IceGatheringState]] internal slot, initialized to "new".

  21. Let connection have an [[ConnectionState]] internal slot, initialized to "new".

  22. Let connection have a [[PendingLocalDescription]] internal slot, initialized to null.

  23. Let connection have a [[CurrentLocalDescription]] internal slot, initialized to null.

  24. Let connection have a [[PendingRemoteDescription]] internal slot, initialized to null.

  25. Let connection have a [[CurrentRemoteDescription]] internal slot, initialized to null.

  26. Let connection have a [[LocalIceCredentialsToReplace]] internal slot, initialized to an empty set.

  27. Return connection.

4.4.1.2 Chain an asynchronous operation

An RTCPeerConnection object has an operations chain, [[Operations]], which ensures that only one asynchronous operation in the chain executes concurrently. If subsequent calls are made while the returned promise of a previous call is still not settled, they are added to the chain and executed when all the previous calls have finished executing and their promises have settled.

To chain an operation to an RTCPeerConnection object's operations chain, run the following steps:

  1. Let connection be the RTCPeerConnection object.

  2. If connection.[[IsClosed]] is true, return a promise rejected with a newly created InvalidStateError.

  3. Let operation be the operation to be chained.

  4. Let p be a new promise.

  5. Append operation to [[Operations]].

  6. If the length of [[Operations]] is exactly 1, execute operation.

  7. Upon fulfillment or rejection of the promise returned by the operation, run the following steps:

    1. If connection.[[IsClosed]] is true, abort these steps.

    2. If the promise returned by operation was fulfilled with a value, fulfill p with that value.

    3. If the promise returned by operation was rejected with a value, reject p with that value.

    4. Upon fulfillment or rejection of p, execute the following steps:

      1. If connection.[[IsClosed]] is true, abort these steps.

      2. Remove the first element of [[Operations]].

      3. If [[Operations]] is non-empty, execute the operation represented by the first element of [[Operations]], and abort these steps.

      4. If connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] is false, abort these steps.

      5. Set connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] to false.

      6. Update the negotiation-needed flag for connection.

  8. Return p.

4.4.1.3 Update the connection state

An RTCPeerConnection object has an aggregated [[ConnectionState]]. Whenever the state of an RTCDtlsTransport changes, the user agent MUST queue a task that runs the following steps:

  1. Let connection be this RTCPeerConnection object associated with the RTCDtlsTransport object whose state changed.

  2. Proposed Correction 35:Don't fire connectionstatechange on pc.close() (PR #2876)

    If connection.[[IsClosed]] is true, abort these steps.

  3. Let newState be the value of deriving a new state value as described by the RTCPeerConnectionState enum.

  4. If connection.[[ConnectionState]] is equal to newState, abort these steps.

  5. Set connection.[[ConnectionState]] to newState.

  6. Fire an event named connectionstatechange at connection.

4.4.1.4 Set the session description

To set a local session description description on an RTCPeerConnection object connection, set the session description description on connection with the additional value false.

To set a remote session description description on an RTCPeerConnection object connection, set the session description description on connection with the additional value true.

To set a session description description on an RTCPeerConnection object connection, given a remote boolean, run the following steps:

  1. Let p be a new promise.

  2. If description.type is "rollback" and connection.[[SignalingState]] is either "stable", "have-local-pranswer", or "have-remote-pranswer", then reject p with a newly created InvalidStateError and abort these steps.

  3. Let jsepSetOfTransceivers be a shallow copy of connection's set of transceivers.

  4. In parallel, start the process to apply description as described in [RFC9429] (section 5.5. and section 5.6.), with these additional restrictions:

    1. Use jsepSetOfTransceivers as the source of truth with regard to what "RtpTransceivers" exist, and their [[JsepMid]] internal slot as their "mid property".

    2. Candidate Correction 5:Forbid ICE gathering and connectivity checks on administrative prohibited candidates (PR #2708)

      If remote is false and this triggers the ICE candidate gathering process in [RFC9429] (section 5.9.), the ICE Agent MUST NOT gather candidates that would be administratively prohibited.

    3. Candidate Correction 5:Forbid ICE gathering and connectivity checks on administrative prohibited candidates (PR #2708)

      If remote is true and this triggers ICE connectivity checks in [RFC9429] (section 5.10.), the ICE Agent MUST NOT attempt to connect to candidates that are administratively prohibited.

    4. If remote is true, validate back-to-back offers as if answers were applied in between, by running the check for subsequent offers as if it were in stable state.

    5. If applying description leads to modifying a transceiver transceiver, and transceiver.[[Sender]].[[SendEncodings]] is non-empty, and not equal to the encodings that would result from processing description, the process of applying description fails. This specification does not allow remotely initiated RID renegotiation.

       
    6. If the process to apply description fails for any reason, then the user agent MUST queue a task that runs the following steps:

      1. If connection.[[IsClosed]] is true, then abort these steps.

      2. If description.type is invalid for the current connection.[[SignalingState]] as described in [RFC9429] (section 5.5. and section 5.6.), then reject p with a newly created InvalidStateError and abort these steps.

      3. If the content of description is not valid SDP syntax, then reject p with an RTCError (with errorDetail set to "sdp-syntax-error" and the sdpLineNumber attribute set to the line number in the SDP where the syntax error was detected) and abort these steps.

      4. If remote is true, the connection's RTCRtcpMuxPolicy is require and the description does not use RTCP mux, then reject p with a newly created InvalidAccessError and abort these steps.

      5. If the description attempted to renegotiate RIDs, as described above, then reject p with a newly created InvalidAccessError and abort these steps.

      6. If the content of description is invalid, then reject p with a newly created InvalidAccessError and abort these steps.

      7. For all other errors, reject p with a newly created OperationError.

    7. If description is applied successfully, the user agent MUST queue a task that runs the following steps:

      1. If connection.[[IsClosed]] is true, then abort these steps.

      2. If remote is true and description is of type "offer", then if any addTrack() methods on connection succeeded during the process to apply description, abort these steps and start the process over as if they had succeeded prior, to include the extra transceiver(s) in the process.

      3. If any promises from setParameters methods on RTCRtpSenders associated with connection are not settled, abort these steps and start the process over.

      4. If description is of type "offer" and connection.[[SignalingState]] is "stable" then for each transceiver in connection's set of transceivers, run the following steps:

        1. Set transceiver.[[Sender]].[[LastStableStateSenderTransport]] to transceiver.[[Sender]].[[SenderTransport]].

        2. Candidate Correction 13:Rollback restores ridless encoding trounced by sRD(simulcastOffer). (PR #2797)

          If transceiver.[[Sender]].[[SendEncodings]].length is 1 and the lone encoding contains no rid member, then set transceiver.[[Sender]].[[LastStableRidlessSendEncodings]] to transceiver.[[Sender]].[[SendEncodings]]; Otherwise, set transceiver.[[Sender]].[[LastStableRidlessSendEncodings]] to null.

        3. Set transceiver.[[Receiver]].[[LastStableStateReceiverTransport]] to transceiver.[[Receiver]].[[ReceiverTransport]].

        4. Set transceiver.[[Receiver]].[[LastStableStateAssociatedRemoteMediaStreams]] to transceiver.[[Receiver]].[[AssociatedRemoteMediaStreams]].

        5. Set transceiver.[[Receiver]].[[LastStableStateReceiveCodecs]] to transceiver.[[Receiver]].[[ReceiveCodecs]].

      5. If remote is false, then run one of the following steps:

        1. If description is of type "offer", set connection.[[PendingLocalDescription]] to a new RTCSessionDescription object constructed from description, set connection.[[SignalingState]] to "have-local-offer", and release early candidates.

        2. If description is of type "answer", then this completes an offer answer negotiation. Set connection.[[CurrentLocalDescription]] to a new RTCSessionDescription object constructed from description, and set connection.[[CurrentRemoteDescription]] to connection.[[PendingRemoteDescription]]. Set both connection.[[PendingRemoteDescription]] and connection.[[PendingLocalDescription]] to null. Set both connection.[[LastCreatedOffer]] and connection.[[LastCreatedAnswer]] to "", set connection.[[SignalingState]] to "stable", and release early candidates. Finally, if none of the ICE credentials in connection.[[LocalIceCredentialsToReplace]] are present in description, then set connection.[[LocalIceCredentialsToReplace]] to an empty set.

        3. If description is of type "pranswer", then set connection.[[PendingLocalDescription]] to a new RTCSessionDescription object constructed from description, set connection.[[SignalingState]] to "have-local-pranswer", and release early candidates.

      6. Otherwise, (if remote is true) run one of the following steps:

        1. If description is of type "offer", set connection.[[PendingRemoteDescription]] attribute to a new RTCSessionDescription object constructed from description, and set connection.[[SignalingState]] to "have-remote-offer".

        2. If description is of type "answer", then this completes an offer answer negotiation. Set connection.[[CurrentRemoteDescription]] to a new RTCSessionDescription object constructed from description, and set connection.[[CurrentLocalDescription]] to connection.[[PendingLocalDescription]]. Set both connection.[[PendingRemoteDescription]] and connection.[[PendingLocalDescription]] to null. Set both connection.[[LastCreatedOffer]] and connection.[[LastCreatedAnswer]] to "", and set connection.[[SignalingState]] to "stable". Finally, if none of the ICE credentials in connection.[[LocalIceCredentialsToReplace]] are present in the newly set connection.[[CurrentLocalDescription]], then set connection.[[LocalIceCredentialsToReplace]] to an empty set.

        3. If description is of type "pranswer", then set connection.[[PendingRemoteDescription]] to a new RTCSessionDescription object constructed from description and set connection.[[SignalingState]] to "have-remote-pranswer".

      7. If description is of type "answer", and it initiates the closure of an existing SCTP association, as defined in [RFC8841], Sections 10.3 and 10.4, set the value of connection.[[SctpTransport]] to null.

      8. Let trackEventInits, muteTracks, addList, removeList and errorList be empty lists.

      9. If description is of type "answer" or "pranswer", then run the following steps:

        1. If description initiates the establishment of a new SCTP association, as defined in [RFC8841], Sections 10.3 and 10.4, create an RTCSctpTransport with an initial state of "connecting" and assign the result to the [[SctpTransport]] slot. Otherwise, if an SCTP association is established, but the max-message-size SDP attribute is updated, update the data max message size of connection.[[SctpTransport]].

        2. If description negotiates the DTLS role of the SCTP transport, then for each RTCDataChannel, channel, with a null id, run the following step:

          1. Give channel a new ID generated according to [RFC8832]. If no available ID could be generated, set channel.[[ReadyState]] to "closed", and add channnel to errorList.
      10. If description is not of type "rollback", then run the following steps:

        1. If remote is false, then run the following steps for each media description in description:

          Candidate Correction 26:Prune createAnswer()'s encodings and SendEncodings in sLD(answer). (PR #2801)
          1. If the media description was not yet associated with an RTCRtpTransceiver object then run the following steps:

            1. Let transceiver be the RTCRtpTransceiver used to create the media description.

            2. Set transceiver.[[Mid]] to transceiver.[[JsepMid]].

            3. If transceiver.[[Stopped]] is true, abort these sub steps.

            4. If the media description is indicated as using an existing media media transport according to [RFC8843], let transport be the RTCDtlsTransport object representing the RTP/RTCP component of that transport.

            5. Otherwise, let transport be a newly created RTCDtlsTransport object with a new underlying RTCIceTransport.

            6. Set transceiver.[[Sender]].[[SenderTransport]] to transport.

            7. Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.

          2. Let transceiver be the RTCRtpTransceiver associated with the media description.

          3. If transceiver.[[Stopped]] is true, abort these sub steps.

          4. Let direction be an RTCRtpTransceiverDirection value representing the direction from the media media description.

          5. If direction is "sendrecv" or "recvonly", set transceiver.[[Receptive]] to true, otherwise set it to false.

          6. Set transceiver.[[Receiver]].[[ReceiveCodecs]] to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.

            Note

            If the direction is "sendonly" or "inactive", the receiver is not prepared to receive anything, and the list will be empty.

          7. If description is of type "answer" or "pranswer", then run the following steps:

            1. If transceiver. [[Sender]].[[SendEncodings]] .length is greater than 1, then run the following steps:

              1. If description is missing all of the previously negotiated layers, then remove all dictionaries in transceiver.[[Sender]].[[SendEncodings]] except the first one, and skip the next step.

              2. If description is missing any of the previously negotiated layers, then remove the dictionaries that correspond to the missing layers from transceiver.[[Sender]].[[SendEncodings]].

            2. Set transceiver.[[Sender]].[[SendCodecs]] to the codecs that description negotiates for sending and which the user agent is currently capable of sending, and set transceiver.[[Sender]].[[LastReturnedParameters]] to null.

            3. If direction is "sendonly" or "inactive", and transceiver.[[FiredDirection]] is either "sendrecv" or "recvonly", then run the following steps:

              1. Set the associated remote streams given transceiver.[[Receiver]], an empty list, another empty list, and removeList.

              2. process the removal of a remote remote track for the media description, given transceiver and muteTracks.

            4. Set transceiver.[[CurrentDirection]] and transceiver.[[FiredDirection]] to direction.

        2. Otherwise, (if remote is true) run the following steps for each media description in description:

          Candidate Correction 12:Remove interaction between encoding.active and simulcast ~rid (PR #2754)
          Candidate Correction 14:Make RTCTransceiver.direction reflects local preference in offers and answers (PR #2759)
          Candidate Correction 22:Allow remote offer rid pruning of encodings through the client answer. (PR #2758)
          Candidate Correction 37:Don't fail sRD(offer) over rid mismatch, just answer with unicast. (PR #2794)
          Candidate Correction 25:Remove duplicate rids in proposedSendEncodings. (PR #2800)
          Candidate Correction 27:Ignore comma-separated rid alternatives. (PR #2813)
          1. If the description is of type "offer" and the media description contains a request to receive simulcast, use the order of the rid values specified in the simulcast attribute to create an RTCRtpEncodingParameters dictionary for each of the simulcast layers, populating the rid member according to the corresponding rid valuevalue (using only the first value if comma-separated alternatives exist), and let sendEncodingsproposedSendEncodings be the list the list containing the created dictionaries. Otherwise, let sendEncodings proposedSendEncodings be an an empty list.

          2. For each encoding, encoding, in proposedSendEncodings in reverse order, if encoding's rid matches that of another encoding in proposedSendEncodings, remove encoding from proposedSendEncodings.

          3. Let supportedEncodings be the maximum number of encodings that the implementation can support. If the length of sendEncodingsproposedSendEncodings is greater than supportedEncodings, truncate sendEncodingsproposedSendEncodings so that its length is supportedEncodings.
          4. If sendEncodingsproposedSendEncodings is non-empty, set set each encoding's scaleResolutionDownBy to 2^(length of sendEncodingsproposedSendEncodings - encoding index - 1).
          5. As described by [RFC8829RFC9429] (section 5.10.), attempt to find an existing RTCRtpTransceiver object, transceiver, to represent the media description.

          6. If a suitable transceiver was found (transceiver is set), and sendEncodingsproposedSendEncodings is non-empty, set transceiver.[[Sender]].[[SendEncodings]] to sendEncodings, and set transceiver.[[Sender]].[[LastReturnedParameters]] to null.run the following steps:

            1. If the length of transceiver.[[Sender]].[[SendEncodings]] is 1, and the lone encoding contains no rid member, set transceiver.[[Sender]].[[SendEncodings]] to proposedSendEncodings, and set transceiver.[[Sender]].[[LastReturnedParameters]] to null.

          7. If no suitable transceiver was found (transceiver is unset), run the following steps:

            1. Create an RTCRtpSender, sender, from the media media description using sendEncodingsproposedSendEncodings.

            2. Create an RTCRtpReceiver, receiver, from the media media description.

            3. Create an RTCRtpTransceiver with sender, receiver and an RTCRtpTransceiverDirection value of "recvonly", and let transceiver be the result.

            4. Add transceiver to the connection's set of of transceivers.

          8. If description is of type "answer" or "pranswer", and transceiver. [[Sender]].[[SendEncodings]] .length is greater than 1, then run the following steps:

            1. If description indicates that simulcast is not supported or desired, or description is missing all of the previously negotiated layers, then remove all dictionaries in transceiver.[[Sender]].[[SendEncodings]] except the first one and abort these sub steps.

            2. If description rejects is missing any of the offered previously negotiated layers, then then remove the the dictionaries that correspond to rejected to the missing layers from transceiver.[[Sender]].[[SendEncodings]].

            3. Update the paused status as indicated by [RFC8853] of each simulcast layer by setting the active member on the corresponding dictionaries in transceiver.[[Sender]].[[SendEncodings]] to true for unpaused or to false for paused.

          9. Set transceiver.[[Mid]] to transceiver.[[JsepMid]].

          10. Let direction be an RTCRtpTransceiverDirection value representing the direction from the media media description, but with the send and receive directions reversed to represent this peer's point of view. If the media description is rejected, set direction to "inactive".

          11. If direction is "sendrecv" or "recvonly", let msids be a list of the MSIDs that the media description indicates transceiver.[[Receiver]].[[ReceiverTrack]] is to be associated with. Otherwise, let msids be an empty list.

            Note
            msids will be an empty list here if media description is rejected.
          12. Process remote tracks with transceiver, direction, msids, addList, removeList, and trackEventInits.

          13. Set transceiver.[[Receiver]].[[ReceiveCodecs]] to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.

          14. If description is of type "answer" or "pranswer", then run the following steps:

            1. Set transceiver.[[Sender]].[[SendCodecs]] to the codecs that description negotiates for sending and which the user agent is currently capable of sending.

            2. Set transceiver.[[CurrentDirection]] and transceiver.[[Direction]]s to direction.

            3. Let transport be the RTCDtlsTransport object representing the RTP/RTCP component of the media media transport used by transceiver's associated media description, according to [RFC8843].

            4. Set transceiver.[[Sender]].[[SenderTransport]] to transport.

            5. Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.

            6. Set the [[IceRole]] of transport according to the rules of [RFC8445].

              Note
              The rules of [RFC8445] that apply here are: This ensures that [[IceRole]] always has a value after the first offer is processed.
          15. If the media description is rejected, and transceiver.[[Stopped]] is false, then stop the the RTCRtpTransceiver transceiver.

      11. Otherwise, (if description is of type "rollback") run the following steps:

        1. Let pendingDescription be either connection.[[PendingLocalDescription]] or connection.[[PendingRemoteDescription]], whichever one is not null.

        2. For each transceiver in the connection's set of transceivers run the following steps:

          1. If transceiver was not associated with a media description prior to pendingDescription being set, disassociate it and set both transceiver.[[JsepMid]] and transceiver.[[Mid]] to null.

          2. Set transceiver.[[Sender]].[[SenderTransport]] to transceiver.[[Sender]].[[LastStableStateSenderTransport]].

          3. Candidate Correction 13:Rollback restores ridless encoding trounced by sRD(simulcastOffer). (PR #2797)

            If transceiver.[[Sender]].[[LastStableRidlessSendEncodings]] is not null, and any encoding in transceiver.[[Sender]].[[SendEncodings]] contains a rid member, then set transceiver.[[Sender]].[[SendEncodings]] to transceiver.[[Sender]].[[LastStableRidlessSendEncodings]].

          4. Set transceiver.[[Receiver]].[[ReceiverTransport]] to transceiver.[[Receiver]].[[LastStableStateReceiverTransport]].

          5. Set transceiver.[[Receiver]].[[ReceiveCodecs]] to transceiver.[[Receiver]].[[LastStableStateReceiveCodecs]].

          6. If connection.[[SignalingState]] is "have-remote-offer", run the following sub steps:

            1. Let msids be a list of the ids of all MediaStream objects in transceiver.[[Receiver]].[[LastStableStateAssociatedRemoteMediaStreams]], or an empty list if there are none.

            2. Process remote tracks with transceiver, transceiver.[[CurrentDirection]], msids, addList, removeList, and trackEventInits.

          7. If transceiver was created when pendingDescription was set, and a track has never been attached to it via addTrack(), then stop the RTCRtpTransceiver transceiver, and remove it from connection's set of transceivers.

        3. Set connection.[[PendingLocalDescription]] and connection.[[PendingRemoteDescription]] to null, and set connection.[[SignalingState]] to "stable".

      12. If description is of type "answer", then run the following steps:

        1. For each transceiver in the connection's set of transceivers run the following steps:

          1. If transceiver is stopped, associated with an m= section and the associated m= section is rejected in connection.[[CurrentLocalDescription]] or connection.[[CurrentRemoteDescription]], remove the transceiver from the connection's set of transceivers.

      13. If connection.[[SignalingState]] is now "stable", run the following steps:

        1. For any transceiver that was removed from the set of transceivers in a previous step, if any of its transports (transceiver.[[Sender]].[[SenderTransport]] or transceiver.[[Receiver]].[[ReceiverTransport]]) are still not closed and they're no longer referenced by a non-stopped transceiver, close the RTCDtlsTransports and their associated RTCIceTransports. This results in events firing on these objects in a queued task.

        2. Candidate Addition 49:Add codec to RTCRtpEncodingParameters (PR #2985)

          For each transceiver in connection's set of transceivers:

          1. Let codecs be transceiver.[[Sender]].[[SendCodecs]].

          2. If codecs is not an empty list:

            1. For each encoding in transceiver.[[Sender]].[[SendEncodings]], if encoding.codec does not match any entry in codecs, remove encoding[codec].

        3. Clear the negotiation-needed flag and update the negotiation-needed flag.

      14. If connection.[[SignalingState]] changed above, fire an event named signalingstatechange at connection.

      15. For each channel in errorList, fire an event named error using the RTCErrorEvent interface with the errorDetail attribute set to "data-channel-failure" at channel.

      16. For each track in muteTracks, set the muted state of track to the value true.

      17. For each stream and track pair in removeList, remove the track track from stream.

      18. For each stream and track pair in addList, add the track track to stream.

      19. For each entry entry in trackEventInits, fire an event named track using the RTCTrackEvent interface with its receiver attribute initialized to entry.receiver, its track attribute initialized to entry.track, its streams attribute initialized to entry.streams and its transceiver attribute initialized to entry.transceiver at the connection object.

      20. Resolve p with undefined.

  5. Return p.

4.4.1.5 Set the configuration

To set a configuration with configuration, run the following steps:

Proposed Correction 1:Set default values of the RTCConfiguration dictionary, aligning it with current implementations (PR #2691)
Proposed Correction 6:Validate ICE transport settings upfront when setting a configuration (PR #2689)
  1. Let configuration be the RTCConfiguration dictionary to be processed.

  2. Let connection be the target RTCPeerConnection object.

  3. Let oldConfig be connection.[[Configuration]].

  4. If configuration.certificates oldConfig is setnot null, run the the following steps:, and if any of them fail, throw an InvalidModificationError:

    1. If the length of configuration.certificates is different from the length of connectionoldConfig.[[Configuration]].certificates, throw an InvalidModificationErrorfail.

    2. Let index be initialized to 0.

    3. Let size be initialized to the length of configuration.certificates.

    4. While index is less than size, run the following steps: length of configuration.

      certificates, run the following steps:

      1. If the ECMAScript object represented by the value of configuration.certificates at index is not the same as the ECMAScript object represented by the value of connectionoldConfig.[[Configuration]].certificates at index, throw an InvalidModificationErrorthen fail.

      2. Increment index by 1.

    5. If the value of configuration.bundlePolicy differs from oldConfig.bundlePolicy, then fail.

    6. If the value of configuration.rtcpMuxPolicy differs from oldConfig.rtcpMuxPolicy, then fail.

    7. If the value of configuration.iceCandidatePoolSize differs from oldConfig.iceCandidatePoolSize, and setLocalDescription has already been called, then fail.

  5. If the value of configuration.bundlePolicy is set and its value differs from the connection's bundle policy, throw an InvalidModificationError.

  6. If the value of configuration.rtcpMuxPolicy is set and its value differs from the connection's rtcpMux policy, throw an InvalidModificationError.

  7. If the value of configuration.iceCandidatePoolSize is set and its value differs from the connection's previously set iceCandidatePoolSize, and setLocalDescription has already been called, throw an InvalidModificationError.

  8. Let iceServers be configuration.iceServers.

  9. Truncate iceServers to the maximum number of supported elements.

  10. For each server in iceServers, run the following steps:

    1. Let urls be server.urls.

    2. If urls is a string, set urls to a list consisting of just that string.

    3. If urls is empty, throw a "SyntaxError" DOMException.

    4. For each url in urls, run the validate an ICE server URL algorithm on url.

  11. Set the ICE Agent's ICE transports setting to the value of configuration.iceTransportPolicy. As defined in [RFC8829RFC9429] (section 4.1.18.), if the new ICE ICE transports setting changes the existing setting, no action will be taken until the next gathering phase. If a script wants this to happen immediately, it should do an ICE restart.

  12. Set the ICE Agent's prefetched ICE candidate pool size as defined in [RFC8829RFC9429] (section 3.5.4. and section 4.1.1.) to the value of configuration.iceCandidatePoolSize. If the new ICE candidate pool size changes the existing setting, this may result in immediate gathering of new pooled candidates, or discarding of existing pooled candidates, as defined in [RFC8829RFC9429] (section 4.1.18.).

  13. Let validatedServers be an empty list.

  14. If configuration.iceServers is defined, then run the following steps for each element:

    1. Let server be the current list element.

    2. Let urls be server.urls.

    3. If urls is a string, set urls to a list consisting of just that string.

    4. If urls is empty, throw a SyntaxError.

    5. For each url in urls, run the [=validate an ICE server URL=] algorithm on url.

    6. Append server to validatedServers.

  15. Set the ICE Agent's ICE servers list to validatedServersto iceServers.

    As defined in [RFC8829RFC9429] (section 4.1.18.), if a new list of servers replaces the ICE Agent's existing ICE servers listICE servers list, no action will be taken until the next gathering phase. If a script wants this to happen immediately, it should do an ICE restart. However, if the ICE ICE candidate pool has a nonzero size, any existing existing pooled candidates will be discarded, and new candidates will be gathered from the new servers.

  16. Store configuration in the [[Configuration]] internal slot.

To validate an ICE server URL url, run the following steps:

Candidate Correction 33:Use the url spec to parse ice server urls (PR #2853)
  1. Parse the url using the generic URI syntax defined in [RFC3986] and obtain the scheme name. If the parsing based on the syntax defined in [RFC3986] fails, throw a SyntaxError. If the scheme name is not implemented by the browser throw a NotSupportedError. If scheme name is turn or turns, and parsing the url using the syntax defined in [RFC7065] fails, throw a SyntaxError. If scheme name is stun or stuns, and parsing the url using the syntax defined in [RFC7064] fails, throw a SyntaxError.

  2. Let parsedURL be the result of parsing url.

  3. If any of the following conditions apply, then throw a "SyntaxError" DOMException:

    • parsedURL is failure
    • parsedURL's scheme is neither "stun", "stuns", "turn", nor "turns"
    • parsedURL does not have an opaque path
    • parsedURL's' fragment is non-null
    • parsedURL's' scheme is "stun" or "stuns", and parsedURL's' query is non-null
  4. If parsedURL's scheme is not implemented by the user agent, then throw a NotSupportedError.

  5. Let hostAndPortURL be result of parsing the concatenation of "https://" and parsedURL's path.

  6. If hostAndPortURL is failure, then throw a "SyntaxError" DOMException.

    Note

    For "stun" and "stuns" schemes, this validates [RFC7064] section 3.1.
    For "turn" and "turns" schemes, this and the steps below validate [RFC7065] section 3.1.

  7. TODO: validate ?transport=udp|tcp (see PR #2996)
  8. If scheme nameparsedURL's' scheme is turn"turn" or turnsor "turns", and either of server.username or server.credential are omitteddo not exist, then throw an InvalidAccessError.

  9. If scheme name is turn or turns, and server.credentialType is "password", and server.credential is not a DOMString, then throw an InvalidAccessError.

4.4.2 Interface Definition

The RTCPeerConnection interface presented in this section is extended by several partial interfaces throughout this specification. Notably, the RTP Media API section, which adds the APIs to send and receive MediaStreamTrack objects.

WebIDL[Exposed=Window]
interface RTCPeerConnection : EventTarget  {
  constructor(optional RTCConfiguration configuration = {});
  Promise<RTCSessionDescriptionInit> createOffer(optional RTCOfferOptions options = {});
  Promise<RTCSessionDescriptionInit> createAnswer(optional RTCAnswerOptions options = {});
  Promise<undefined> setLocalDescription(optional RTCLocalSessionDescriptionInit description = {});
  readonly attribute RTCSessionDescription? localDescription;
  readonly attribute RTCSessionDescription? currentLocalDescription;
  readonly attribute RTCSessionDescription? pendingLocalDescription;
  Promise<undefined> setRemoteDescription(RTCSessionDescriptionInit description);
  readonly attribute RTCSessionDescription? remoteDescription;
  readonly attribute RTCSessionDescription? currentRemoteDescription;
  readonly attribute RTCSessionDescription? pendingRemoteDescription;
  Promise<undefined> addIceCandidate(optional RTCIceCandidateInit candidate = {});
  readonly attribute RTCSignalingState signalingState;
  readonly attribute RTCIceGatheringState iceGatheringState;
  readonly attribute RTCIceConnectionState iceConnectionState;
  readonly attribute RTCPeerConnectionState connectionState;
  readonly attribute boolean? canTrickleIceCandidates;
  undefined restartIce();
  RTCConfiguration getConfiguration();
  undefined setConfiguration(optional RTCConfiguration configuration = {});
  undefined close();
  attribute EventHandler onnegotiationneeded;
  attribute EventHandler onicecandidate;
  attribute EventHandler onicecandidateerror;
  attribute EventHandler onsignalingstatechange;
  attribute EventHandler oniceconnectionstatechange;
  attribute EventHandler onicegatheringstatechange;
  attribute EventHandler onconnectionstatechange;

  // Legacy Interface Extensions
  // Supporting the methods in this section is optional.
  // If these methods are supported
  // they must be implemented as defined
  // in section "Legacy Interface Extensions"
  Promise<undefined> createOffer(RTCSessionDescriptionCallback successCallback,
                            RTCPeerConnectionErrorCallback failureCallback,
                            optional RTCOfferOptions options = {});
  Promise<undefined> setLocalDescription(RTCLocalSessionDescriptionInit description,
                                    VoidFunction successCallback,
                                    RTCPeerConnectionErrorCallback failureCallback);
  Promise<undefined> createAnswer(RTCSessionDescriptionCallback successCallback,
                             RTCPeerConnectionErrorCallback failureCallback);
  Promise<undefined> setRemoteDescription(RTCSessionDescriptionInit description,
                                     VoidFunction successCallback,
                                     RTCPeerConnectionErrorCallback failureCallback);
  Promise<undefined> addIceCandidate(RTCIceCandidateInit candidate,
                                VoidFunction successCallback,
                                RTCPeerConnectionErrorCallback failureCallback);
};
Attributes
localDescription of type RTCSessionDescription, readonly, nullable

The localDescription attribute MUST return [[PendingLocalDescription]] if it is not null and otherwise it MUST return [[CurrentLocalDescription]].

Note that [[CurrentLocalDescription]].sdp and [[PendingLocalDescription]].sdp need not be string-wise identical to the sdp value passed to the corresponding setLocalDescription call (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).

currentLocalDescription of type RTCSessionDescription, readonly, nullable

The currentLocalDescription attribute MUST return [[CurrentLocalDescription]].

It represents the local description that was successfully negotiated the last time the RTCPeerConnection transitioned into the stable state plus any local candidates that have been generated by the ICE Agent since the offer or answer was created.

pendingLocalDescription of type RTCSessionDescription, readonly, nullable

The pendingLocalDescription attribute MUST return [[PendingLocalDescription]].

It represents a local description that is in the process of being negotiated plus any local candidates that have been generated by the ICE Agent since the offer or answer was created. If the RTCPeerConnection is in the stable state, the value is null.

remoteDescription of type RTCSessionDescription, readonly, nullable

The remoteDescription attribute MUST return [[PendingRemoteDescription]] if it is not null and otherwise it MUST return [[CurrentRemoteDescription]].

Note that [[CurrentRemoteDescription]].sdp and [[PendingRemoteDescription]].sdp need not be string-wise identical to the sdp value passed to the corresponding setRemoteDescription call (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).

currentRemoteDescription of type RTCSessionDescription, readonly, nullable

The currentRemoteDescription attribute MUST return [[CurrentRemoteDescription]].

It represents the last remote description that was successfully negotiated the last time the RTCPeerConnection transitioned into the stable state plus any remote candidates that have been supplied via addIceCandidate() since the offer or answer was created.

pendingRemoteDescription of type RTCSessionDescription, readonly, nullable

The pendingRemoteDescription attribute MUST return [[PendingRemoteDescription]].

It represents a remote description that is in the process of being negotiated, complete with any remote candidates that have been supplied via addIceCandidate() since the offer or answer was created. If the RTCPeerConnection is in the stable state, the value is null.

signalingState of type RTCSignalingState, readonly

The signalingState attribute MUST return the RTCPeerConnection object's [[SignalingState]].

iceGatheringState of type RTCIceGatheringState, readonly

The iceGatheringState attribute MUST return the RTCPeerConnection object's [[IceGatheringState]].

iceConnectionState of type RTCIceConnectionState, readonly

The iceConnectionState attribute MUST return the RTCPeerConnection object's [[IceConnectionState]].

connectionState of type RTCPeerConnectionState, readonly

The connectionState attribute MUST return the RTCPeerConnection object's [[ConnectionState]].

canTrickleIceCandidates of type boolean, readonly, nullable

The canTrickleIceCandidates attribute indicates whether the remote peer is able to accept trickled ICE candidates [RFC8838]. The value is determined based on whether a remote description indicates support for trickle ICE, as defined in [RFC9429] (section 4.1.17.). Prior to the completion of setRemoteDescription, this value is null.

onnegotiationneeded of type EventHandler
The event type of this event handler is negotiationneeded.
onicecandidate of type EventHandler
The event type of this event handler is icecandidate.
onicecandidateerror of type EventHandler
The event type of this event handler is icecandidateerror.
onsignalingstatechange of type EventHandler
The event type of this event handler is signalingstatechange.
oniceconnectionstatechange of type EventHandler
The event type of this event handler is iceconnectionstatechange
onicegatheringstatechange of type EventHandler
The event type of this event handler is icegatheringstatechange.
onconnectionstatechange of type EventHandler
The event type of this event handler is connectionstatechange.
Methods
createOffer

The createOffer method generates a blob of SDP that contains an RFC 3264 offer with the supported configurations for the session, including descriptions of the local MediaStreamTracks attached to this RTCPeerConnection, the codec/RTP/RTCP capabilities supported by this implementation, and parameters of the ICE agent and the DTLS connection. The options parameter may be supplied to provide additional control over the offer generated.

If a system has limited resources (e.g. a finite number of decoders), createOffer needs to return an offer that reflects the current state of the system, so that setLocalDescription will succeed when it attempts to acquire those resources. The session descriptions MUST remain usable by setLocalDescription without causing an error until at least the end of the fulfillment callback of the returned promise.

Creating the SDP MUST follow the appropriate process for generating an offer described in [RFC9429], except the user agent MUST treat a stopping transceiver as stopped for the purposes of RFC9429 in this case.

As an offer, the generated SDP will contain the full set of codec/RTP/RTCP capabilities supported or preferred by the session (as opposed to an answer, which will include only a specific negotiated subset to use). In the event createOffer is called after the session is established, createOffer will generate an offer that is compatible with the current session, incorporating any changes that have been made to the session since the last complete offer-answer exchange, such as addition or removal of tracks. If no changes have been made, the offer will include the capabilities of the current local description as well as any additional capabilities that could be negotiated in an updated offer.

The generated SDP will also contain the ICE agent's usernameFragment, password and ICE options (as defined in [RFC5245], Section 14) and may also contain any local candidates that have been gathered by the agent.

The certificates value in configuration for the RTCPeerConnection provides the certificates configured by the application for the RTCPeerConnection. These certificates, along with any default certificates are used to produce a set of certificate fingerprints. These certificate fingerprints are used in the construction of SDP.

The process of generating an SDP exposes a subset of the media capabilities of the underlying system, which provides generally persistent cross-origin information on the device. It thus increases the fingerprinting surface of the application. In privacy-sensitive contexts, browsers can consider mitigations such as generating SDP matching only a common subset of the capabilities. (This is a fingerprinting vector.)

When the method is called, the user agent MUST run the following steps:

  1. Let connection be the RTCPeerConnection object on which the method was invoked.

  2. If connection.[[IsClosed]] is true, return a promise rejected with a newly created InvalidStateError.

  3. Return the result of chaining the result of creating an offer with connection to connection's operations chain.

To create an offer given connection run the following steps:

  1. If connection.[[SignalingState]] is neither "stable" nor "have-local-offer", return a promise rejected with a newly created InvalidStateError.

  2. Let p be a new promise.

  3. In parallel, begin the in-parallel steps to create an offer given connection and p.

  4. Return p.

The in-parallel steps to create an offer given connection and a promise p are as follows:

  1. If connection was not constructed with a set of certificates, and one has not yet been generated, wait for it to be generated.

  2. Inspect the offerer's system state to determine the currently available resources as necessary for generating the offer, as described in [RFC9429] (section 4.1.8.).

  3. If this inspection failed for any reason, reject p with a newly created OperationError and abort these steps.

  4. Queue a task that runs the final steps to create an offer given connection and p.

The final steps to create an offer given connection and a promise p are as follows:

  1. If connection.[[IsClosed]] is true, then abort these steps.

  2. If connection was modified in such a way that additional inspection of the offerer's system state is necessary, then in parallel begin the in-parallel steps to create an offer again, given connection and p, and abort these steps.

    Note
    This may be necessary if, for example, createOffer was called when only an audio RTCRtpTransceiver was added to connection, but while performing the in-parallel steps to create an offer, a video RTCRtpTransceiver was added, requiring additional inspection of video system resources.
  3. Given the information that was obtained from previous inspection, the current state of connection and its RTCRtpTransceivers, generate an SDP offer, sdpString, as described in [RFC9429] (section 5.2.).

    1. As described in [RFC8843] (Section 7), if bundling is used (see RTCBundlePolicy) an offerer tagged m= section must be selected in order to negotiate a BUNDLE group. The user agent MUST choose the m= section that corresponds to the first non-stopped transceiver in the set of transceivers as the offerer tagged m= section. This allows the remote endpoint to predict which transceiver is the offerer tagged m= section without having to parse the SDP.

    2. The codec preferences of a media description's associated transceiver, transceiver, is said to be the value of transceiver.[[PreferredCodecs]] with the following filtering applied (or said not to be set if transceiver.[[PreferredCodecs]] is empty):

      1. Let kind be transceiver's [[Receiver]]'s [[ReceiverTrack]]'s kind.

      2. If transceiver.direction is "sendonly" or "sendrecv", exclude any codecs not included in the list of implemented send codecs for kind.

      3. If transceiver.direction is "recvonly" or "sendrecv", exclude any codecs not included in the list of implemented receive codecs for kind.

      The filtering MUST NOT change the order of the codec preferences.

    3. If the length of the [[SendEncodings]] slot of the RTCRtpSender is larger than 1, then for each encoding given in [[SendEncodings]] of the RTCRtpSender, add an a=rid send line to the corresponding media section, and add an a=simulcast:send line giving the RIDs in the same order as given in the encodings field. No RID restrictions are set.

      Note

      [RFC8853] section 5.2 specifies that the order of RIDs in the a=simulcast line suggests a proposed order of preference. If the browser decides not to transmit all encodings, one should expect it to stop sending the last encoding in the list first.

  4. Let offer be a newly created RTCSessionDescriptionInit dictionary with its type member initialized to the string "offer" and its sdp member initialized to sdpString.

  5. Set the [[LastCreatedOffer]] internal slot to sdpString.

  6. Resolve p with offer.

createAnswer

The createAnswer method generates an [SDP] answer with the supported configuration for the session that is compatible with the parameters in the remote configuration. Like createOffer, the returned blob of SDP contains descriptions of the local MediaStreamTracks attached to this RTCPeerConnection, the codec/RTP/RTCP options negotiated for this session, and any candidates that have been gathered by the ICE Agent. The options parameter may be supplied to provide additional control over the generated answer.

Like createOffer, the returned description SHOULD reflect the current state of the system. The session descriptions MUST remain usable by setLocalDescription without causing an error until at least the end of the fulfillment callback of the returned promise.

As an answer, the generated SDP will contain a specific codec/RTP/RTCP configuration that, along with the corresponding offer, specifies how the media plane should be established. The generation of the SDP MUST follow the appropriate process for generating an answer described in [RFC9429].

The generated SDP will also contain the ICE agent's usernameFragment, password and ICE options (as defined in [RFC5245], Section 14) and may also contain any local candidates that have been gathered by the agent.

The certificates value in configuration for the RTCPeerConnection provides the certificates configured by the application for the RTCPeerConnection. These certificates, along with any default certificates are used to produce a set of certificate fingerprints. These certificate fingerprints are used in the construction of SDP.

An answer can be marked as provisional, as described in [RFC9429] (section 4.1.10.1.), by setting the type to "pranswer".

When the method is called, the user agent MUST run the following steps:

  1. Let connection be the RTCPeerConnection object on which the method was invoked.

  2. If connection.[[IsClosed]] is true, return a promise rejected with a newly created InvalidStateError.

  3. Return the result of chaining the result of creating an answer with connection to connection's operations chain.

To create an answer given connection run the following steps:

  1. If connection.[[SignalingState]] is neither "have-remote-offer" nor "have-local-pranswer", return a promise rejected with a newly created InvalidStateError.

  2. Let p be a new promise.

  3. In parallel, begin the in-parallel steps to create an answer given connection and p.

  4. Return p.

The in-parallel steps to create an answer given connection and a promise p are as follows:

  1. If connection was not constructed with a set of certificates, and one has not yet been generated, wait for it to be generated.

  2. Inspect the answerer's system state to determine the currently available resources as necessary for generating the answer, as described in [RFC9429] (section 4.1.9.).

  3. If this inspection failed for any reason, reject p with a newly created OperationError and abort these steps.

  4. Queue a task that runs the final steps to create an answer given p.

The final steps to create an answer given a promise p are as follows:

  1. If connection.[[IsClosed]] is true, then abort these steps.

  2. If connection was modified in such a way that additional inspection of the answerer's system state is necessary, then in parallel begin the in-parallel steps to create an answer again given connection and p, and abort these steps.

    Note
    This may be necessary if, for example, createAnswer was called when an RTCRtpTransceiver's direction was "recvonly", but while performing the in-parallel steps to create an answer, the direction was changed to "sendrecv", requiring additional inspection of video encoding resources.
  3. Given the information that was obtained from previous inspection and the current state of connection and its RTCRtpTransceivers, generate an SDP answer, sdpString, as described in [RFC9429] (section 5.3.).

    Candidate Correction 26:Prune createAnswer()'s encodings and SendEncodings in sLD(answer). (PR #2801)
    Candidate Correction 27:Ignore comma-separated rid alternatives. (PR #2813)
    1. The codec preferences of an m= section's associated transceiver associated transceiver, transceiver, is said to be the value of the RTCRtpTransceivertransceiver.[[PreferredCodecs]] with the following filtering applied (or said not to be set if if transceiver.[[PreferredCodecs]] is empty):

      1. If the direction is "sendrecv", exclude any codecs not included in the intersection of RTCRtpSender.getCapabilities(kind).codecs and RTCRtpReceiver.getCapabilities(kind).codecs.

      2. Let kind be transceiver's [[Receiver]]'s [[ReceiverTrack]]'s kind.

      3. If the If transceiver.direction is is "sendonly" or "sendrecv", exclude any codecs not included in RTCRtpSender.getCapabilities(kind).in the list of implemented send codecs for kind.

      4. If the If transceiver.direction is is "recvonly" or "sendrecv", exclude any codecs not included in RTCRtpReceiver.getCapabilities(kind).in the list of implemented receive codecs for kind.

      The filtering MUST NOT change the order of the codec preferences.

    2. If the length of the [[SendEncodings]] slot of the RTCRtpSender is larger than 1, then for each encoding given in [[SendEncodings]] of the RTCRtpSender, add an a=rid send line to the corresponding media section, and add an a=simulcast:send line giving the RIDs in the same order as given in the encodings field. No RID restrictions are set.

    3. If this is an answer to an offer to receive simulcast, then for each media section requesting to receive simulcast, run the following steps:

      1. If the a=simulcast attribute contains comma-separated alternatives for RIDs, remove all but the first ones.

      2. If there are any identically named RIDs in the a=simulcast attribute, remove all but the first one. No RID restrictions are set.

      3. Exclude from the media section in the answer any RID not found in the corresponding transceiver's [[Sender]].[[SendEncodings]].

      Note

      When a setRemoteDescription(offer) establishes a sender's proposed envelope, the sender's [[SendEncodings]] is updated in "have-remote-offer", exposing it to rollback. However, once a simulcast envelope has been established for the sender, subsequent pruning of the sender's [[SendEncodings]] happen when this answer is set with setLocalDescription.

  4. Let answer be a newly created RTCSessionDescriptionInit dictionary with its type member initialized to the string "answer" and its sdp member initialized to sdpString.

  5. Set the [[LastCreatedAnswer]] internal slot to sdpString.

  6. Resolve p with answer.

setLocalDescription

The setLocalDescription method instructs the RTCPeerConnection to apply the supplied RTCLocalSessionDescriptionInit as the local description.

This API changes the local media state. In order to successfully handle scenarios where the application wants to offer to change from one media format to a different, incompatible format, the RTCPeerConnection MUST be able to simultaneously support use of both the current and pending local descriptions (e.g. support codecs that exist in both descriptions) until a final answer is received, at which point the RTCPeerConnection can fully adopt the pending local description, or rollback to the current description if the remote side rejected the change.

Passing in a description is optional. If left out, then setLocalDescription will implicitly create an offer or create an answer, as needed. As noted in [RFC9429] (section 5.4.), if a description with SDP is passed in, that SDP is not allowed to have changed from when it was returned from either createOffer or createAnswer.

When the method is invoked, the user agent MUST run the following steps:

  1. Let description be the method's first argument.

  2. Let connection be the RTCPeerConnection object on which the method was invoked.

  3. Let sdp be description.sdp.

  4. Return the result of chaining the following steps to connection's operations chain:

    1. Let type be description.type if present, or "offer" if not present and connection.[[SignalingState]] is either "stable", "have-local-offer", or "have-remote-pranswer"; otherwise "answer".

    2. If type is "offer", and sdp is not the empty string and not equal to connection.[[LastCreatedOffer]], then return a promise rejected with a newly created InvalidModificationError and abort these steps.

    3. If type is "answer" or "pranswer", and sdp is not the empty string and not equal to connection.[[LastCreatedAnswer]], then return a promise rejected with a newly created InvalidModificationError and abort these steps.

    4. If sdp is the empty string, and type is "offer", then run the following sub steps:

      1. Set sdp to the value of connection.[[LastCreatedOffer]].

      2. If sdp is the empty string, or if it no longer accurately represents the offerer's system state of connection, then let p be the result of creating an offer with connection, and return the result of reacting to p with a fulfillment step that sets the local session description indicated by its first argument.

    5. If sdp is the empty string, and type is "answer" or "pranswer", then run the following sub steps:

      1. Set sdp to the value of connection.[[LastCreatedAnswer]].

      2. If sdp is the empty string, or if it no longer accurately represents the answerer's system state of connection, then let p be the result of creating an answer with connection, and return the result of reacting to p with the following fulfillment steps:

        1. Let answer be the first argument to these fulfillment steps.

        2. Return the result of setting the local session description indicated by {type, answer.sdp}.

    6. Return the result of setting the local session description indicated by {type, sdp}.

Note

As noted in [RFC9429] (section 5.9.), calling this method may trigger the ICE candidate gathering process by the ICE Agent.

setRemoteDescription

The setRemoteDescription method instructs the RTCPeerConnection to apply the supplied RTCSessionDescriptionInit as the remote offer or answer. This API changes the local media state.

When the method is invoked, the user agent MUST run the following steps:

  1. Let description be the method's first argument.

  2. Let connection be the RTCPeerConnection object on which the method was invoked.

  3. Return the result of chaining the following steps to connection's operations chain:

    1. If description.type is "offer" and is invalid for the current connection.[[SignalingState]] as described in [RFC9429] (section 5.5. and section 5.6.), then run the following sub steps:

      1. Let p be the result of setting the local session description indicated by {type: "rollback"}.

      2. Return the result of reacting to p with a fulfillment step that sets the remote session description description, and abort these steps.

    2. Return the result of setting the remote session description description.

addIceCandidate

The addIceCandidate method provides a remote candidate to the ICE Agent. This method can also be used to indicate the end of remote candidates when called with an empty string for the candidate member. The only members of the argument used by this method are candidate, sdpMid, sdpMLineIndex, and usernameFragment; the rest are ignored. When the method is invoked, the user agent MUST run the following steps:

  1. Let candidate be the method's argument.

  2. Let connection be the RTCPeerConnection object on which the method was invoked.

  3. If candidate.candidate is not an empty string and both candidate.sdpMid and candidate.sdpMLineIndex are null, return a promise rejected with a newly created TypeError.

  4. Return the result of chaining the following steps to connection's operations chain:

    1. If remoteDescription is null return a promise rejected with a newly created InvalidStateError.

    2. If candidate.sdpMid is not null, run the following steps:

      1. If candidate.sdpMid is not equal to the mid of any media description in remoteDescription, return a promise rejected with a newly created OperationError.

    3. Else, if candidate.sdpMLineIndex is not null, run the following steps:

      1. If candidate.sdpMLineIndex is equal to or larger than the number of media descriptions in remoteDescription, return a promise rejected with a newly created OperationError.

    4. If either candidate.sdpMid or candidate.sdpMLineIndex indicate a media description in remoteDescription whose associated transceiver is stopped, return a promise resolved with undefined.

    5. If candidate.usernameFragment is not null, and is not equal to any username fragment present in the corresponding media description of an applied remote description, return a promise rejected with a newly created OperationError.

    6. Let p be a new promise.

    7. In parallel, if the candidate is not administratively prohibited, add the ICE candidate candidate as described in [RFC9429] (section 4.1.19.). Use candidate.usernameFragment to identify the ICE generation; if usernameFragment is null, process the candidate for the most recent ICE generation.

      If candidate.candidate is an empty string, process candidate as an end-of-candidates indication for the corresponding media description and ICE candidate generation. If both candidate.sdpMid and candidate.sdpMLineIndex are null, then this end-of-candidates indication applies to all media descriptions.

      1. If candidate could not be successfully added the user agent MUST queue a task that runs the following steps:

        1. If connection.[[IsClosed]] is true, then abort these steps.

        2. Reject p with a newly created OperationError and abort these steps.

      2. If candidate is applied successfully, or if the candidate was administratively prohibited the user agent MUST queue a task that runs the following steps:

        1. If connection.[[IsClosed]] is true, then abort these steps.

        2. If connection.[[PendingRemoteDescription]] is not null, and represents the ICE generation for which candidate was processed, add candidate to connection.[[PendingRemoteDescription]].sdp.

        3. If connection.[[CurrentRemoteDescription]] is not null, and represents the ICE generation for which candidate was processed, add candidate to connection.[[CurrentRemoteDescription]].sdp.

        4. Resolve p with undefined.

    8. Return p.

A candidate is administratively prohibited if the UA has decided not to allow connection attempts to this address.

For privacy reasons, there is no indication to the developer about whether or not an address/port is blocked; it behaves exactly as if there was no response from the address.

The UA MUST prohibit connections to addresses on the [Fetch] block bad port list, and MAY choose to prohibit connections to other addresses.

If the iceTransportPolicy member of the RTCConfiguration is relay, candidates requiring external resolution, such as mDNS candidates and DNS candidates, MUST be prohibited.

Note

Due to WebIDL processing, addIceCandidate(null) is interpreted as a call with the default dictionary present, which, in the above algorithm, indicates end-of-candidates for all media descriptions and ICE candidate generation. This is by design for legacy reasons.

restartIce

The restartIce method tells the RTCPeerConnection that ICE should be restarted. Subsequent calls to createOffer will create descriptions that will restart ICE, as described in section 9.1.1.1 of [RFC5245].

When this method is invoked, the user agent MUST run the following steps:

  1. Let connection be the RTCPeerConnection on which the method was invoked.

  2. Empty connection.[[LocalIceCredentialsToReplace]], and populate it with all ICE credentials (ice-ufrag and ice-pwd as defined in section 15.4 of [RFC5245]) found in connection.[[CurrentLocalDescription]], as well as all ICE credentials found in connection.[[PendingLocalDescription]].

  3. Update the negotiation-needed flag for connection.

getConfiguration

Returns an RTCConfiguration object representing the current configuration of this RTCPeerConnection object.

When this method is called, the user agent MUST return the RTCConfiguration object stored in the [[Configuration]] internal slot.

setConfiguration

The setConfiguration method updates the configuration of this RTCPeerConnection object. This includes changing the configuration of the ICE Agent. As noted in [RFC9429] (section 3.5.1.), when the ICE configuration changes in a way that requires a new gathering phase, an ICE restart is required.

When the setConfiguration method is invoked, the user agent MUST run the following steps:

  1. Let connection be the RTCPeerConnection on which the method was invoked.

  2. If connection.[[IsClosed]] is true, throw an InvalidStateError.

  3. Set the configuration specified by configuration.

close

When the close method is invoked, the user agent MUST run the following steps:

  1. Let connection be the RTCPeerConnection object on which the method was invoked.

  2. close the connection with connection and the value false.

The close the connection algorithm given a connection and a disappear boolean, is as follows:

  1. If connection.[[IsClosed]] is true, abort these steps.

  2. Set connection.[[IsClosed]] to true.

  3. Set connection.[[SignalingState]] to "closed". This does not fire any event.

  4. Let transceivers be the result of executing the CollectTransceivers algorithm. For every RTCRtpTransceiver transceiver in transceivers, run the following steps:

    1. If transceiver.[[Stopped]] is true, abort these sub steps.

    2. Stop the RTCRtpTransceiver with transceiver and disappear.

  5. Set the [[ReadyState]] slot of each of connection's RTCDataChannels to "closed".

    Note
    The RTCDataChannels will be closed abruptly and the closing procedure will not be invoked.
  6. If connection.[[SctpTransport]] is not null, tear down the underlying SCTP association by sending an SCTP ABORT chunk and set the [[SctpTransportState]] to "closed".

  7. Set the [[DtlsTransportState]] slot of each of connection's RTCDtlsTransports to "closed".

  8. Destroy connection's ICE Agent, abruptly ending any active ICE processing and releasing any relevant resources (e.g. TURN permissions).

  9. Set the [[IceTransportState]] slot of each of connection's RTCIceTransports to "closed".

  10. Set connection.[[IceConnectionState]] to "closed". This does not fire any event.

  11. Set connection.[[ConnectionState]] to "closed". This does not fire any event.

4.4.3 Legacy Interface Extensions

Note
The IDL definition of these methods are documented in the main definition of the RTCPeerConnection interface since overloaded functions are not allowed to be defined in partial interfaces.

Supporting the methods in this section is optional. However, if these methods are supported it is mandatory to implement according to what is specified here.

Note
The addStream method that used to exist on RTCPeerConnection is easy to polyfill as:
RTCPeerConnection.prototype.addStream = function(stream) {
  stream.getTracks().forEach((track) => this.addTrack(track, stream));
};
4.4.3.1 Method extensions
Methods
createOffer

When the createOffer method is called, the user agent MUST run the following steps:

  1. Let successCallback be the method's first argument.

  2. Let failureCallback be the callback indicated by the method's second argument.

  3. Let options be the callback indicated by the method's third argument.

  4. Run the steps specified by RTCPeerConnection's createOffer() method with options as the sole argument, and let p be the resulting promise.

  5. Upon fulfillment of p with value offer, invoke successCallback with offer as the argument.

  6. Upon rejection of p with reason r, invoke failureCallback with r as the argument.

  7. Return a promise resolved with undefined.

setLocalDescription

When the setLocalDescription method is called, the user agent MUST run the following steps:

  1. Let description be the method's first argument.

  2. Let successCallback be the callback indicated by the method's second argument.

  3. Let failureCallback be the callback indicated by the method's third argument.

  4. Run the steps specified by RTCPeerConnection's setLocalDescription method with description as the sole argument, and let p be the resulting promise.

  5. Upon fulfillment of p, invoke successCallback with undefined as the argument.

  6. Upon rejection of p with reason r, invoke failureCallback with r as the argument.

  7. Return a promise resolved with undefined.

createAnswer
Note
The legacy createAnswer method does not take an RTCAnswerOptions parameter, since no known legacy createAnswer implementation ever supported it.

When the createAnswer method is called, the user agent MUST run the following steps:

  1. Let successCallback be the method's first argument.

  2. Let failureCallback be the callback indicated by the method's second argument.

  3. Run the steps specified by RTCPeerConnection's createAnswer() method with no arguments, and let p be the resulting promise.

  4. Upon fulfillment of p with value answer, invoke successCallback with answer as the argument.

  5. Upon rejection of p with reason r, invoke failureCallback with r as the argument.

  6. Return a promise resolved with undefined.

setRemoteDescription

When the setRemoteDescription method is called, the user agent MUST run the following steps:

  1. Let description be the method's first argument.

  2. Let successCallback be the callback indicated by the method's second argument.

  3. Let failureCallback be the callback indicated by the method's third argument.

  4. Run the steps specified by RTCPeerConnection's setRemoteDescription method with description as the sole argument, and let p be the resulting promise.

  5. Upon fulfillment of p, invoke successCallback with undefined as the argument.

  6. Upon rejection of p with reason r, invoke failureCallback with r as the argument.

  7. Return a promise resolved with undefined.

addIceCandidate

When the addIceCandidate method is called, the user agent MUST run the following steps:

  1. Let candidate be the method's first argument.

  2. Let successCallback be the callback indicated by the method's second argument.

  3. Let failureCallback be the callback indicated by the method's third argument.

  4. Run the steps specified by RTCPeerConnection's addIceCandidate() method with candidate as the sole argument, and let p be the resulting promise.

  5. Upon fulfillment of p, invoke successCallback with undefined as the argument.

  6. Upon rejection of p with reason r, invoke failureCallback with r as the argument.

  7. Return a promise resolved with undefined.

Callback Definitions

These callbacks are only used on the legacy APIs.

RTCPeerConnectionErrorCallback
WebIDLcallback RTCPeerConnectionErrorCallback = undefined (DOMException error);
Callback RTCPeerConnectionErrorCallback Parameters
error of type DOMException
An error object encapsulating information about what went wrong.
RTCSessionDescriptionCallback
WebIDLcallback RTCSessionDescriptionCallback = undefined (RTCSessionDescriptionInit description);
Callback RTCSessionDescriptionCallback Parameters
description of type RTCSessionDescriptionInit
The object containing the SDP [SDP].
4.4.3.2 Legacy configuration extensions

This section describes a set of legacy extensions that may be used to influence how an offer is created, in addition to the media added to the RTCPeerConnection. Developers are encouraged to use the RTCRtpTransceiver API instead.

When createOffer is called with any of the legacy options specified in this section, run the followings steps instead of the regular createOffer steps:

  1. Let options be the methods first argument.

  2. Let connection be the current RTCPeerConnection object.

  3. For each offerToReceive<Kind> member in options with kind, kind, run the following steps:

    1. If the value of the dictionary member is false,
      1. For each non-stopped "sendrecv" transceiver of transceiver kind kind, set transceiver.[[Direction]] to "sendonly".

      2. For each non-stopped "recvonly" transceiver of transceiver kind kind, set transceiver.[[Direction]] to "inactive".

      Continue with the next option, if any.

    2. If connection has any non-stopped "sendrecv" or "recvonly" transceivers of transceiver kind kind, continue with the next option, if any.

    3. Let transceiver be the result of invoking the equivalent of connection.addTransceiver(kind), except that this operation MUST NOT update the negotiation-needed flag.

    4. If transceiver is unset because the previous operation threw an error, abort these steps.

    5. Set transceiver.[[Direction]] to "recvonly".

  4. Run the steps specified by createOffer to create the offer.

WebIDLpartial dictionary RTCOfferOptions {
  boolean offerToReceiveAudio;
  boolean offerToReceiveVideo;
};
Attributes
offerToReceiveAudio of type boolean

This setting provides additional control over the directionality of audio. For example, it can be used to ensure that audio can be received, regardless if audio is sent or not.

offerToReceiveVideo of type boolean

This setting provides additional control over the directionality of video. For example, it can be used to ensure that video can be received, regardless if video is sent or not.

4.4.4 Garbage collection

An RTCPeerConnection object MUST not be garbage collected as long as any event can cause an event handler to be triggered on the object. When the object's [[IsClosed]] internal slot is true, no such event handler can be triggered and it is therefore safe to garbage collect the object.

All RTCDataChannel and MediaStreamTrack objects that are connected to an RTCPeerConnection have a strong reference to the RTCPeerConnection object.

4.5 Error Handling

4.5.1 General Principles

All methods that return promises are governed by the standard error handling rules of promises. Methods that do not return promises may throw exceptions to indicate errors.

4.6 Session Description Model

4.6.1 RTCSdpType

The RTCSdpType enum describes the type of an RTCSessionDescriptionInit, RTCLocalSessionDescriptionInit, or RTCSessionDescription instance.

WebIDLenum RTCSdpType {
  "offer",
  "pranswer",
  "answer",
  "rollback"
};
RTCSdpType Enumeration description
Enum valueDescription
offer

An RTCSdpType of "offer" indicates that a description MUST be treated as an [SDP] offer.

pranswer

An RTCSdpType of "pranswer" indicates that a description MUST be treated as an [SDP] answer, but not a final answer. A description used as an SDP pranswer may be applied as a response to an SDP offer, or an update to a previously sent SDP pranswer.

answer

An RTCSdpType of "answer" indicates that a description MUST be treated as an [SDP] final answer, and the offer-answer exchange MUST be considered complete. A description used as an SDP answer may be applied as a response to an SDP offer or as an update to a previously sent SDP pranswer.

rollback

An RTCSdpType of "rollback" indicates that a description MUST be treated as canceling the current SDP negotiation and moving the SDP [SDP] offer back to what it was in the previous stable state. Note the local or remote SDP descriptions in the previous stable state could be null if there has not yet been a successful offer-answer negotiation. An "answer" or "pranswer" cannot be rolled back.

4.6.2 RTCSessionDescription Class

The RTCSessionDescription class is used by RTCPeerConnection to expose local and remote session descriptions.

WebIDL[Exposed=Window]
interface RTCSessionDescription {
  constructor(RTCSessionDescriptionInit descriptionInitDict);
  readonly attribute RTCSdpType type;
  readonly attribute DOMString sdp;
  [Default] RTCSessionDescriptionInit toJSON();
};
Constructors
constructor()

The RTCSessionDescription() constructor takes a dictionary argument, description, whose content is used to initialize the new RTCSessionDescription object. This constructor is deprecated; it exists for legacy compatibility reasons only.

Attributes
type of type RTCSdpType, readonly
The type of this session description.
sdp of type DOMString, readonly, defaulting to ""
The string representation of the SDP [SDP].
Methods
toJSON()
When called, run [WEBIDL]'s default toJSON steps.
WebIDLdictionary RTCSessionDescriptionInit {
  required RTCSdpType type;
  DOMString sdp = "";
};
Dictionary RTCSessionDescriptionInit Members
type of type RTCSdpType, required
The type of this session description.
sdp of type DOMString
The string representation of the SDP [SDP]; if type is "rollback", this member is unused.
WebIDLdictionary RTCLocalSessionDescriptionInit {
  RTCSdpType type;
  DOMString sdp = "";
};
Dictionary RTCLocalSessionDescriptionInit Members
type of type RTCSdpType
The type of this description. If not present, then setLocalDescription will infer the type based on the RTCPeerConnection's [[SignalingState]].
sdp of type DOMString
The string representation of the SDP [SDP]; if type is "rollback", this member is unused.

4.7 Session Negotiation Model

Many changes to state of an RTCPeerConnection will require communication with the remote side via the signaling channel, in order to have the desired effect. The app can be kept informed as to when it needs to do signaling, by listening to the negotiationneeded event. This event is fired according to the state of the connection's negotiation-needed flag, represented by a [[NegotiationNeeded]] internal slot.

4.7.1 Setting Negotiation-Needed

This section is non-normative.

If an operation is performed on an RTCPeerConnection that requires signaling, the connection will be marked as needing negotiation. Examples of such operations include adding or stopping an RTCRtpTransceiver, or adding the first RTCDataChannel.

Internal changes within the implementation can also result in the connection being marked as needing negotiation.

Note that the exact procedures for updating the negotiation-needed flag are specified below.

4.7.2 Clearing Negotiation-Needed

This section is non-normative.

The negotiation-needed flag is cleared when a session description of type "answer" is set successfully, and the supplied description matches the state of the RTCRtpTransceivers and RTCDataChannels that currently exist on the RTCPeerConnection. Specifically, this means that all non-stopped transceivers have an associated section in the local description with matching properties, and, if any data channels have been created, a data section exists in the local description.

Note that the exact procedures for updating the negotiation-needed flag are specified below.

4.7.3 Updating the Negotiation-Needed flag

The process below occurs where referenced elsewhere in this document. It also may occur as a result of internal changes within the implementation that affect negotiation. If such changes occur, the user agent MUST update the negotiation-needed flag.

To update the negotiation-needed flag for connection, run the following steps:

  1. If the length of connection.[[Operations]] is not 0, then set connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] to true, and abort these steps.

  2. Queue a task to run the following steps:

    1. If connection.[[IsClosed]] is true, abort these steps.

    2. If the length of connection.[[Operations]] is not 0, then set connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] to true, and abort these steps.

    3. If connection.[[SignalingState]] is not "stable", abort these steps.

      Note

      The negotiation-needed flag will be updated once the state transitions to "stable", as part of the steps for setting a session description.

    4. If the result of checking if negotiation is needed is false, clear the negotiation-needed flag by setting connection.[[NegotiationNeeded]] to false, and abort these steps.

    5. If connection.[[NegotiationNeeded]] is already true, abort these steps.

    6. Set connection.[[NegotiationNeeded]] to true.

    7. Fire an event named negotiationneeded at connection.

    Note

    The task queueing prevents negotiationneeded from firing prematurely, in the common situation where multiple modifications to connection are being made at once.

    Additionally, we avoid racing with negotiation methods by only firing negotiationneeded when the operations chain is empty.

To check if negotiation is needed for connection, perform the following checks:

  1. If any implementation-specific negotiation is required, as described at the start of this section, return true.

  2. If connection.[[LocalIceCredentialsToReplace]] is not empty, return true.

  3. Let description be connection.[[CurrentLocalDescription]].

  4. If connection has created any RTCDataChannels, and no m= section in description has been negotiated yet for data, return true.

  5. For each transceiver in connection's set of transceivers, perform the following checks:

    1. If transceiver.[[Stopping]] is true and transceiver.[[Stopped]] is false, return true.

    2. If transceiver isn't stopped and isn't yet associated with an m= section in description, return true.

    3. If transceiver isn't stopped and is associated with an m= section in description then perform the following checks:

      1. If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the associated m= section in description either doesn't contain a single a=msid line, or the number of MSIDs from the a=msid lines in this m= section, or the MSID values themselves, differ from what is in transceiver.sender.[[AssociatedMediaStreamIds]], return true.

      2. If description is of type "offer", and the direction of the associated m= section in neither connection.[[CurrentLocalDescription]] nor connection.[[CurrentRemoteDescription]] matches transceiver.[[Direction]], return true. In this step, when the direction is compared with a direction found in [[CurrentRemoteDescription]], the description's direction must be reversed to represent the peer's point of view.

      3. If description is of type "answer", and the direction of the associated m= section in the description does not match transceiver.[[Direction]] intersected with the offered direction (as described in [RFC9429] (section 5.3.1.)), return true.

    4. If transceiver is stopped and is associated with an m= section, but the associated m= section is not yet rejected in connection.[[CurrentLocalDescription]] or connection.[[CurrentRemoteDescription]], return true.

  6. If all the preceding checks were performed and true was not returned, nothing remains to be negotiated; return false.

4.8 Interfaces for Interactive Connectivity Establishment

4.8.1 RTCIceCandidate Interface

This interface describes an ICE candidate, described in [RFC5245] Section 2. Other than candidate, sdpMid, sdpMLineIndex, and usernameFragment, the remaining attributes are derived from parsing the candidate member in candidateInitDict, if it is well formed.

Candidate Addition 16:Add RTCIceCandidate.relayProtocol (PR #2763)
Candidate Addition 23:Add RTCIceCandidate.url (PR #2773)
[Exposed=Window]
interface RTCIceCandidate {
  constructor(optional RTCIceCandidateInit candidateInitDict = {});
  readonly attribute DOMString candidate;
  readonly attribute DOMString? sdpMid;
  readonly attribute unsigned short? sdpMLineIndex;
  readonly attribute DOMString? foundation;
  readonly attribute RTCIceComponent? component;
  readonly attribute unsigned long? priority;
  readonly attribute DOMString? address;
  readonly attribute RTCIceProtocol? protocol;
  readonly attribute unsigned short? port;
  readonly attribute RTCIceCandidateType? type;
  readonly attribute RTCIceTcpCandidateType? tcpType;
  readonly attribute DOMString? relatedAddress;
  readonly attribute unsigned short? relatedPort;
  readonly attribute DOMString? usernameFragment;
  readonly attribute RTCIceServerTransportProtocol? relayProtocol;
  readonly attribute DOMString? url;
  RTCIceCandidateInit toJSON();
};
Constructor
constructor()

The RTCIceCandidate() constructor takes a dictionary argument, candidateInitDict, whose content is used to initialize the new RTCIceCandidate object.

When invoked, run the following steps:

  1. If both the sdpMid and sdpMLineIndex members of candidateInitDict are null, throw a TypeError.
  2. Return the result of creating an RTCIceCandidate with candidateInitDict.

To create an RTCIceCandidate with a candidateInitDict dictionary, run the following steps:

  1. Let iceCandidate be a newly created RTCIceCandidate object.
  2. Create internal slots for the following attributes of iceCandidate, initilized to null: foundation, component, priority, address, protocol, port, type, tcpType, relatedAddress, and relatedPort.
  3. Create internal slots for the following attributes of iceCandidate, initilized to their namesakes in candidateInitDict: candidate, sdpMid, sdpMLineIndex, usernameFragment.
  4. Let candidate be the candidate dictionary member of candidateInitDict. If candidate is not an empty string, run the following steps:
    1. Parse candidate using the candidate-attribute grammar.
    2. If parsing of candidate-attribute has failed, abort these steps.
    3. If any field in the parse result represents an invalid value for the corresponding attribute in iceCandidate, abort these steps.
    4. Set the corresponding internal slots in iceCandidate to the field values of the parsed result.
  5. Return iceCandidate.
Note

The constructor for RTCIceCandidate only does basic parsing and type checking for the dictionary members in candidateInitDict. Detailed validation on the well-formedness of candidate, sdpMid, sdpMLineIndex, usernameFragment with the corresponding session description is done when passing the RTCIceCandidate object to addIceCandidate().

To maintain backward compatibility, any error on parsing the candidate attribute is ignored. In such case, the candidate attribute holds the raw candidate string given in candidateInitDict, but derivative attributes such as foundation, priority, etc are set to null.

Attributes

Most attributes below are defined in section 15.1 of [RFC5245].

candidate of type DOMString, readonly
This carries the candidate-attribute as defined in section 15.1 of [RFC5245]. If this RTCIceCandidate represents an end-of-candidates indication or a peer reflexive remote candidate, candidate is an empty string.
sdpMid of type DOMString, readonly, nullable
If not null, this contains the media stream "identification-tag" defined in [RFC5888] for the media component this candidate is associated with.
sdpMLineIndex of type unsigned short, readonly, nullable
If not null, this indicates the index (starting at zero) of the media description in the SDP this candidate is associated with.
foundation of type DOMString, readonly, nullable
A unique identifier that allows ICE to correlate candidates that appear on multiple RTCIceTransports.
component of type RTCIceComponent, readonly, nullable
The assigned network component of the candidate ("rtp" or "rtcp"). This corresponds to the component-id field in candidate-attribute, decoded to the string representation as defined in RTCIceComponent.
priority of type unsigned long, readonly, nullable
The assigned priority of the candidate.
address of type DOMString, readonly, nullable

The address of the candidate, allowing for IPv4 addresses, IPv6 addresses, and fully qualified domain names (FQDNs). This corresponds to the connection-address field in candidate-attribute.

Remote candidates may be exposed, for instance via [[SelectedCandidatePair]].remote. By default, the user agent MUST leave the address attribute as null for any exposed remote candidate. Once a RTCPeerConnection instance learns on an address by the web application using addIceCandidate, the user agent can expose the address attribute value in any RTCIceCandidate of the RTCPeerConnection instance representing a remote candidate with that newly learnt address.

Note

The addresses exposed in candidates gathered via ICE and made visibile to the application in RTCIceCandidate instances can reveal more information about the device and the user (e.g. location, local network topology) than the user might have expected in a non-WebRTC enabled browser.

These addresses are always exposed to the application, and potentially exposed to the communicating party, and can be exposed without any specific user consent (e.g. for peer connections used with data channels, or to receive media only).

These addresses can also be used as temporary or persistent cross-origin states, and thus contribute to the fingerprinting surface of the device. (This is a fingerprinting vector.)

Applications can avoid exposing addresses to the communicating party, either temporarily or permanently, by forcing the ICE Agent to report only relay candidates via the iceTransportPolicy member of RTCConfiguration.

To limit the addresses exposed to the application itself, browsers can offer their users different policies regarding sharing local addresses, as defined in [RFC8828].

protocol of type RTCIceProtocol, readonly, nullable
The protocol of the candidate ("udp"/"tcp"). This corresponds to the transport field in candidate-attribute.
port of type unsigned short, readonly, nullable
The port of the candidate.
type of type RTCIceCandidateType, readonly, nullable
The type of the candidate. This corresponds to the candidate-types field in candidate-attribute.
tcpType of type RTCIceTcpCandidateType, readonly, nullable
If protocol is "tcp", tcpType represents the type of TCP candidate. Otherwise, tcpType is null. This corresponds to the tcp-type field in candidate-attribute.
relatedAddress of type DOMString, readonly, nullable
For a candidate that is derived from another, such as a relay or reflexive candidate, the relatedAddress is the IP address of the candidate that it is derived from. For host candidates, the relatedAddress is null. This corresponds to the rel-address field in candidate-attribute.
relatedPort of type unsigned short, readonly, nullable
For a candidate that is derived from another, such as a relay or reflexive candidate, the relatedPort is the port of the candidate that it is derived from. For host candidates, the relatedPort is null. This corresponds to the rel-port field in candidate-attribute.
usernameFragment of type DOMString, readonly, nullable
This carries the ufrag as defined in section 15.4 of [RFC5245].
Candidate Addition 16:Add RTCIceCandidate.relayProtocol (PR #2763)
relayProtocol of type RTCIceServerTransportProtocol, readonly, nullable
For local candidates of type "relay" this is the protocol used by the endpoint to communicate with the TURN server. For all other candidates it is null.
Candidate Addition 23:Add RTCIceCandidate.url (PR #2773)
url of type DOMString, readonly, nullable
For local candidates of type "srflx" or type "relay" this is the URL of the ICE server from which the candidate was obtained. For all other candidates it is null.
Methods
toJSON()
To invoke the toJSON() operation of the RTCIceCandidate interface, run the following steps:
  1. Let json be a new RTCIceCandidateInit dictionary.
  2. For each attribute identifier attr in «candidate, sdpMid, sdpMLineIndex, usernameFragment»:
    1. Let value be the result of getting the underlying value of the attribute identified by attr, given this RTCIceCandidate object.
    2. Set json[attr] to value.
  3. Return json.
WebIDLdictionary RTCIceCandidateInit {
  DOMString candidate = "";
  DOMString? sdpMid = null;
  unsigned short? sdpMLineIndex = null;
  DOMString? usernameFragment = null;
};
Dictionary RTCIceCandidateInit Members
candidate of type DOMString, defaulting to ""
This carries the candidate-attribute as defined in section 15.1 of [RFC5245]. If this represents an end-of-candidates indication, candidate is an empty string.
sdpMid of type DOMString, nullable, defaulting to null
If not null, this contains the media stream "identification-tag" defined in [RFC5888] for the media component this candidate is associated with.
sdpMLineIndex of type unsigned short, nullable, defaulting to null
If not null, this indicates the index (starting at zero) of the media description in the SDP this candidate is associated with.
usernameFragment of type DOMString, nullable, defaulting to null
If not null, this carries the ufrag as defined in section 15.4 of [RFC5245].
4.8.1.1 candidate-attribute Grammar

The candidate-attribute grammar is used to parse the candidate member of candidateInitDict in the RTCIceCandidate() constructor.

The primary grammar for candidate-attribute is defined in section 15.1 of [RFC5245]. In addition, the browser MUST support the grammar extension for ICE TCP as defined in section 4.5 of [RFC6544].

The browser MAY support other grammar extensions for candidate-attribute as defined in other RFCs.

4.8.1.2 RTCIceProtocol Enum

The RTCIceProtocol represents the protocol of the ICE candidate.

WebIDLenum RTCIceProtocol {
  "udp",
  "tcp"
};
RTCIceProtocol Enumeration description
Enum valueDescription
udp A UDP candidate, as described in [RFC5245].
tcp A TCP candidate, as described in [RFC6544].
4.8.1.3 RTCIceTcpCandidateType Enum

The RTCIceTcpCandidateType represents the type of the ICE TCP candidate, as defined in [RFC6544].

WebIDLenum RTCIceTcpCandidateType {
  "active",
  "passive",
  "so"
};
RTCIceTcpCandidateType Enumeration description
Enum valueDescription
active An "active" TCP candidate is one for which the transport will attempt to open an outbound connection but will not receive incoming connection requests.
passive A "passive" TCP candidate is one for which the transport will receive incoming connection attempts but not attempt a connection.
so An "so" candidate is one for which the transport will attempt to open a connection simultaneously with its peer.
Note

The user agent will typically only gather active ICE TCP candidates.

4.8.1.4 RTCIceCandidateType Enum

The RTCIceCandidateType represents the type of the ICE candidate, as defined in [RFC5245] section 15.1.

WebIDLenum RTCIceCandidateType {
  "host",
  "srflx",
  "prflx",
  "relay"
};
RTCIceCandidateType Enumeration description
Enum valueDescription
host A host candidate, as defined in Section 4.1.1.1 of [RFC5245].
srflx A server reflexive candidate, as defined in Section 4.1.1.2 of [RFC5245].
prflx A peer reflexive candidate, as defined in Section 4.1.1.2 of [RFC5245].
relay A relay candidate, as defined in Section 7.1.3.2.1 of [RFC5245].
Candidate Addition 16:Add RTCIceCandidate.relayProtocol (PR #2763)
4.8.1.5 RTCIceServerTransportProtocol Enum

The RTCIceServerTransportProtocol represents the type of the transport protocol used between the client and the server, as defined in [RFC8656] section 3.1.

WebIDLenum RTCIceServerTransportProtocol {
  "udp",
  "tcp",
  "tls",
};
RTCIceServerTransportProtocol Enumeration description
Enum valueDescription
udp The TURN client is using UDP as transport to the server.
tcp The TURN client is using TCP as transport to the server.
tls The TURN client is using TLS as transport to the server.

4.8.2 RTCPeerConnectionIceEvent

The icecandidate event of the RTCPeerConnection uses the RTCPeerConnectionIceEvent interface.

When firing an RTCPeerConnectionIceEvent event that contains an RTCIceCandidate object, it MUST include values for both sdpMid and sdpMLineIndex. If the RTCIceCandidate is of type "srflx" or type "relay", the url property of the event MUST be set to the URL of the ICE server from which the candidate was obtained.

Note
The icecandidate event is used for three different types of indications:
  • A candidate has been gathered. The candidate member of the event will be populated normally. It should be signaled to the remote peer and passed into addIceCandidate.

  • An RTCIceTransport has finished gathering a generation of candidates, and is providing an end-of-candidates indication as defined by Section 8.2 of [RFC8838]. This is indicated by candidate.candidate being set to an empty string. The candidate object should be signaled to the remote peer and passed into addIceCandidate like a typical ICE candidate, in order to provide the end-of-candidates indication to the remote peer.

  • All RTCIceTransports have finished gathering candidates, and the RTCPeerConnection's RTCIceGatheringState has transitioned to "complete". This is indicated by the candidate member of the event being set to null. This only exists for backwards compatibility, and this event does not need to be signaled to the remote peer. It's equivalent to an icegatheringstatechange event with the "complete" state.

WebIDL[Exposed=Window]
interface RTCPeerConnectionIceEvent : Event {
  constructor(DOMString type, optional RTCPeerConnectionIceEventInit eventInitDict = {});
  readonly attribute RTCIceCandidate? candidate;
  readonly attribute DOMString? url;
};
Constructors
RTCPeerConnectionIceEvent.constructor()
Attributes
candidate of type RTCIceCandidate, readonly, nullable

The candidate attribute is the RTCIceCandidate object with the new ICE candidate that caused the event.

This attribute is set to null when an event is generated to indicate the end of candidate gathering.

Note

Even where there are multiple media components, only one event containing a null candidate is fired.

url of type DOMString, readonly, nullable

The url attribute is the STUN or TURN URL that identifies the STUN or TURN server used to gather this candidate. If the candidate was not gathered from a STUN or TURN server, this parameter will be set to null.

Candidate Correction 23:Mark RTCPeerConnectionIceEvent.url as deprecated (PR #2773)

This attribute is deprecated; it exists for legacy compatibility reasons only. Prefer the candidate url.

WebIDLdictionary RTCPeerConnectionIceEventInit : EventInit {
  RTCIceCandidate? candidate;
  DOMString? url;
};
Dictionary RTCPeerConnectionIceEventInit Members
candidate of type RTCIceCandidate, nullable

See the candidate attribute of the RTCPeerConnectionIceEvent interface.

url of type DOMString, nullable
The url attribute is the STUN or TURN URL that identifies the STUN or TURN server used to gather this candidate.

4.8.3 RTCPeerConnectionIceErrorEvent

The icecandidateerror event of the RTCPeerConnection uses the RTCPeerConnectionIceErrorEvent interface.

WebIDL[Exposed=Window]
interface RTCPeerConnectionIceErrorEvent : Event {
  constructor(DOMString type, RTCPeerConnectionIceErrorEventInit eventInitDict);
  readonly attribute DOMString? address;
  readonly attribute unsigned short? port;
  readonly attribute DOMString url;
  readonly attribute unsigned short errorCode;
  readonly attribute USVString errorText;
};
Constructors
RTCPeerConnectionIceErrorEvent.constructor()
Attributes
address of type DOMString, readonly, nullable

The address attribute is the local IP address used to communicate with the STUN or TURN server.

On a multihomed system, multiple interfaces may be used to contact the server, and this attribute allows the application to figure out on which one the failure occurred.

If the local IP address value is not already exposed as part of a local candidate, the address attribute will be set to null.

port of type unsigned short, readonly, nullable

The port attribute is the port used to communicate with the STUN or TURN server.

If the address attribute is null, the port attribute is also set to null.

url of type DOMString, readonly

The url attribute is the STUN or TURN URL that identifies the STUN or TURN server for which the failure occurred.

errorCode of type unsigned short, readonly

The errorCode attribute is the numeric STUN error code returned by the STUN or TURN server [STUN-PARAMETERS].

If no host candidate can reach the server, errorCode will be set to the value 701 which is outside the STUN error code range. This error is only fired once per server URL while in the RTCIceGatheringState of "gathering".

errorText of type USVString, readonly

The errorText attribute is the STUN reason text returned by the STUN or TURN server [STUN-PARAMETERS].

If the server could not be reached, errorText will be set to an implementation-specific value providing details about the error.

WebIDLdictionary RTCPeerConnectionIceErrorEventInit : EventInit {
  DOMString? address;
  unsigned short? port;
  DOMString url;
  required unsigned short errorCode;
  USVString errorText;
};
Dictionary RTCPeerConnectionIceErrorEventInit Members
address of type DOMString, nullable

The local address used to communicate with the STUN or TURN server, or null.

port of type unsigned short, nullable

The local port used to communicate with the STUN or TURN server, or null.

url of type DOMString

The STUN or TURN URL that identifies the STUN or TURN server for which the failure occurred.

errorCode of type unsigned short, required

The numeric STUN error code returned by the STUN or TURN server.

errorText of type USVString

The STUN reason text returned by the STUN or TURN server.

4.9 Certificate Management

The certificates that RTCPeerConnection instances use to authenticate with peers use the RTCCertificate interface. These objects can be explicitly generated by applications using the generateCertificate method and can be provided in the RTCConfiguration when constructing a new RTCPeerConnection instance.

The explicit certificate management functions provided here are optional. If an application does not provide the certificates configuration option when constructing an RTCPeerConnection a new set of certificates MUST be generated by the user agent. That set MUST include an ECDSA certificate with a private key on the P-256 curve and a signature with a SHA-256 hash.

WebIDLpartial interface RTCPeerConnection {
  static Promise<RTCCertificate>
      generateCertificate(AlgorithmIdentifier keygenAlgorithm);
};

Methods

generateCertificate, static

The generateCertificate function causes the user agent to create an X.509 certificate [X509V3] and corresponding private key. A handle to information is provided in the form of the RTCCertificate interface. The returned RTCCertificate can be used to control the certificate that is offered in the DTLS sessions established by RTCPeerConnection.

The keygenAlgorithm argument is used to control how the private key associated with the certificate is generated. The keygenAlgorithm argument uses the WebCrypto [WebCryptoAPI] AlgorithmIdentifier type.

The following values MUST be supported by a user agent: { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, and { name: "ECDSA", namedCurve: "P-256" }.

Note

It is expected that a user agent will have a small or even fixed set of values that it will accept.

The certificate produced by this process also contains a signature. The validity of this signature is only relevant for compatibility reasons. Only the public key and the resulting certificate fingerprint are used by RTCPeerConnection, but it is more likely that a certificate will be accepted if the certificate is well formed. The browser selects the algorithm used to sign the certificate; a browser SHOULD select SHA-256 [FIPS-180-4] if a hash algorithm is needed.

The resulting certificate MUST NOT include information that can be linked to a user or user agent. Randomized values for distinguished name and serial number SHOULD be used.

When the method is called, the user agent MUST run the following steps:

  1. Let keygenAlgorithm be the first argument to generateCertificate.

  2. Let expires be a value of 2592000000 (30*24*60*60*1000)

    Note

    This means the certificate will by default expire in 30 days from the time of the generateCertificate call.

  3. If keygenAlgorithm is an object, run the following steps:

    1. Let certificateExpiration be the result of converting the ECMAScript object represented by keygenAlgorithm to an RTCCertificateExpiration dictionary.

    2. If the conversion fails with an error, return a promise that is rejected with error.

    3. If certificateExpiration.expires is not undefined, set expires to certificateExpiration.expires.

    4. If expires is greater than 31536000000, set expires to 31536000000.

      Note

      This means the certificate cannot be valid for longer than 365 days from the time of the generateCertificate call.

      A user agent MAY further cap the value of expires.

  4. Let normalizedKeygenAlgorithm be the result of normalizing an algorithm with an operation name of generateKey and a supportedAlgorithms value specific to production of certificates for RTCPeerConnection.

  5. If the above normalization step fails with an error, return a promise that is rejected with error.

  6. If the normalizedKeygenAlgorithm parameter identifies an algorithm that the user agent cannot or will not use to generate a certificate for RTCPeerConnection, return a promise that is rejected with a DOMException of type NotSupportedError. In particular, normalizedKeygenAlgorithm MUST be an asymmetric algorithm that can be used to produce a signature used to authenticate DTLS connections.

  7. Let p be a new promise.

  8. Run the following steps in parallel:

    1. Perform the generate key operation specified by normalizedKeygenAlgorithm using keygenAlgorithm.

    2. Let generatedKeyingMaterial and generatedKeyCertificate be the private keying material and certificate generated by the above step.

    3. Let certificate be a new RTCCertificate object.

    4. Set certificate.[[Expires]] to the current time plus expires value.

    5. Set certificate.[[Origin]] to the relevant settings object's origin.

    6. Store the generatedKeyingMaterial in a secure module, and let handle be a reference identifier to it.

    7. Set certificate.[[KeyingMaterialHandle]] to handle.

    8. Set certificate.[[Certificate]] to generatedCertificate.

    9. Resolve p with certificate.

  9. Return p.

Proposed Correction 7:Replace DOMTimeStamp in the definition of the RTCCertificateExpiration.expires and of RTCCertificate.expires, and change its origin to certificate creation time (PR #2686, PR #2700)

4.9.1 RTCCertificateExpiration Dictionary

4.9.1 RTCCertificateExpiration Dictionary

RTCCertificateExpiration is used to set an expiration date on certificates generated by generateCertificate.

dictionary RTCCertificateExpiration {
  [EnforceRange] DOMTimeStamp unsigned long long expires;
};
expires, of type DOMTimeStamp unsigned long long

An optional expires attribute MAY be added to the definition of the algorithm that is passed to generateCertificate. If this parameter is present it indicates the maximum time in milliseconds that the RTCCertificate is valid for relative to for, measured from the current timetime the certificate is created.

Proposed Correction 7:Replace DOMTimeStamp in the definition of the RTCCertificateExpiration.expires and of RTCCertificate.expires, and change its origin to certificate creation time (PR #2686, PR #2700)

4.9.2 RTCCertificate Interface

4.9.2 RTCCertificate Interface

The RTCCertificate interface represents a certificate used to authenticate WebRTC communications. In addition to the visible properties, internal slots contain a handle to the generated private keying materal ([[KeyingMaterialHandle]]), a certificate ([[Certificate]]) that RTCPeerConnection uses to authenticate with a peer, and the origin ([[Origin]]) that created the object.

[Exposed=Window, Serializable]
interface RTCCertificate {
  readonly attribute DOMTimeStamp EpochTimeStamp expires;
  sequence<RTCDtlsFingerprint> getFingerprints();
};
Attributes
Attributes
expires of type DOMTimeStampEpochTimeStamp, readonly

The expires attribute indicates the date and time in milliseconds relative to 1970-01-01T00:00:00Z after which the certificate will be considered invalid by the browser. After this time, attempts to construct an RTCPeerConnection using this certificate fail.

Note that this value might not be reflected in a notAfter parameter in the certificate itself.

Methods
Methods
getFingerprints

Returns the list of certificate fingerprints, one of which is computed with the digest algorithm used in the certificate signature.

For the purposes of this API, the [[Certificate]] slot contains unstructured binary data. No mechanism is provided for applications to access the [[KeyingMaterialHandle]] internal slot or the keying material it references. Implementations MUST support applications storing and retrieving RTCCertificate objects from persistent storage, in a manner that also preserves the keying material referenced by [[KeyingMaterialHandle]]. Implementations SHOULD store the sensitive keying material in a secure module safe from same-process memory attacks. This allows the private key to be stored and used, but not easily read using a memory attack.

RTCCertificate objects are serializable objects [HTML]. Their serialization steps, given value and serialized, are:

  1. Set serialized.[[Expires]] to the value of value.expires attribute.
  2. Set serialized.[[Certificate]] to a copy of the unstructured binary data in value.[[Certificate]].
  3. Set serialized.[[Origin]] to a copy of the unstructured binary data in value.[[Origin]].
  4. Set serialized.[[KeyingMaterialHandle]] to a serialization of the handle in value.[[KeyingMaterialHandle]] (not the private keying material itself).

Their deserialization steps, given serialized and value, are:

  1. Initialize value.expires attribute to contain serialized.[[Expires]].
  2. Set value.[[Certificate]] to a copy of serialized.[[Certificate]].
  3. Set value.[[Origin]] to a copy of serialized.[[Origin]].
  4. Set value.[[KeyingMaterialHandle]] to the private keying material handle resulting from deserializing serialized.[[KeyingMaterialHandle]].
Note

Supporting structured cloning in this manner allows RTCCertificate instances to be persisted to stores. It also allows instances to be passed to other origins using APIs like postMessage(message, options) [html]. However, the object cannot be used by any other origin than the one that originally created it.

5. RTP Media API

The RTP media API lets a web application send and receive MediaStreamTracks over a peer-to-peer connection. Tracks, when added to an RTCPeerConnection, result in signaling; when this signaling is forwarded to a remote peer, it causes corresponding tracks to be created on the remote side.

Note

There is not an exact 1:1 correspondence between tracks sent by one RTCPeerConnection and received by the other. For one, IDs of tracks sent have no mapping to the IDs of tracks received. Also, replaceTrack changes the track sent by an RTCRtpSender without creating a new track on the receiver side; the corresponding RTCRtpReceiver will only have a single track, potentially representing multiple sources of media stitched together. Both addTransceiver and replaceTrack can be used to cause the same track to be sent multiple times, which will be observed on the receiver side as multiple receivers each with its own separate track. Thus it's more accurate to think of a 1:1 relationship between an RTCRtpSender on one side and an RTCRtpReceiver's track on the other side, matching senders and receivers using the RTCRtpTransceiver's mid if necessary.

When sending media, the sender may need to rescale or resample the media to meet various requirements, including the envelope negotiated by SDP, alignment restrictions of the encoder, or even CPU overuse detection or bandwidth estimation.

Following the rules in [RFC9429] (section 3.6.), the video MAY be downscaled. The media MUST NOT be upscaled to create fake data that did not occur in the input source, the media MUST NOT be cropped except as needed to satisfy constraints on pixel counts, and the aspect ratio MUST NOT be changed.

Note

The WebRTC Working Group is seeking implementation feedback on the need and timeline for a more complex handling of this situation. Some possible designs have been discussed in GitHub issue 1283.

Proposed Correction 43:Allow encoder resolution alignment in scaleResolutionDownBy. (PR #2808)

When Whenever video is rescaled, for example for certain combinations of width or height and rescaled as a result of scaleResolutionDownBy values, situations when the resulting width or height is not an integer may occur. In such situations the The user agent MUSTMUST NOT use transmit video larger than the integer part of the resultpart of the scaled width and height from scaleResolutionDownBy, except to respect an encoder's minimum resolution. What to transmit if the integer part of of the scaled width or or height is zero is implementation-specificimplementation-defined.

The actual encoding and transmission of MediaStreamTracks is managed through objects called RTCRtpSenders. Similarly, the reception and decoding of MediaStreamTracks is managed through objects called RTCRtpReceivers. Each RTCRtpSender is associated with at most one track, and each track to be received is associated with exactly one RTCRtpReceiver.

The encoding and transmission of each MediaStreamTrack SHOULD be made such that its characteristics (width, height and frameRate for video tracks; sampleSize, sampleRate and channelCount for audio tracks) are to a reasonable degree retained by the track created on the remote side. There are situations when this does not apply, there may for example be resource constraints at either endpoint or in the network or there may be RTCRtpSender settings applied that instruct the implementation to act differently.

An RTCPeerConnection object contains a set of RTCRtpTransceivers, representing the paired senders and receivers with some shared state. This set is initialized to the empty set when the RTCPeerConnection object is created. RTCRtpSenders and RTCRtpReceivers are always created at the same time as an RTCRtpTransceiver, which they will remain attached to for their lifetime. RTCRtpTransceivers are created implicitly when the application attaches a MediaStreamTrack to an RTCPeerConnection via the addTrack() method, or explicitly when the application uses the addTransceiver method. They are also created when a remote description is applied that includes a new media description. Additionally, when a remote description is applied that indicates the remote endpoint has media to send, the relevant MediaStreamTrack and RTCRtpReceiver are surfaced to the application via the track event.

In order for an RTCRtpTransceiver to send and/or receive media with another endpoint this must be negotiated with SDP such that both endpoints have an RTCRtpTransceiver object that is associated with the same media description.

When creating an offer, enough media descriptions will be generated to cover all transceivers on that end. When this offer is set as the local description, any disassociated transceivers get associated with media descriptions in the offer.

When an offer is set as the remote description, any media descriptions in it not yet associated with a transceiver get associated with a new or existing transceiver. In this case, only disassociated transceivers that were created via the addTrack() method may be associated. Disassociated transceivers created via the addTransceiver() method, however, won't get associated even if media descriptions are available in the remote offer. Instead, new transceivers will be created and associated if there aren't enough addTrack()-created transceivers. This sets addTrack()-created and addTransceiver()-created transceivers apart in a critical way that is not observable from inspecting their attributes.

When creating an answer, only media descriptions that were present in the offer may be listed in the answer. As a consequence, any transceivers that were not associated when setting the remote offer remain disassociated after setting the local answer. This can be remedied by the answerer creating a follow-up offer, initiating another offer/answer exchange, or in the case of using addTrack()-created transceivers, making sure that enough media descriptions are offered in the initial exchange.

5.1 RTCPeerConnection Interface Extensions

The RTP media API extends the RTCPeerConnection interface as described below.

WebIDL          partial interface RTCPeerConnection {
  sequence<RTCRtpSender> getSenders();
  sequence<RTCRtpReceiver> getReceivers();
  sequence<RTCRtpTransceiver> getTransceivers();
  RTCRtpSender addTrack(MediaStreamTrack track, MediaStream... streams);
  undefined removeTrack(RTCRtpSender sender);
  RTCRtpTransceiver addTransceiver((MediaStreamTrack or DOMString) trackOrKind,
                                   optional RTCRtpTransceiverInit init = {});
  attribute EventHandler ontrack;
};

Attributes

ontrack of type EventHandler

The event type of this event handler is track.

Methods

getSenders

Returns a sequence of RTCRtpSender objects representing the RTP senders that belong to non-stopped RTCRtpTransceiver objects currently attached to this RTCPeerConnection object.

When the getSenders method is invoked, the user agent MUST return the result of executing the CollectSenders algorithm.

We define the CollectSenders algorithm as follows:

  1. Let transceivers be the result of executing the CollectTransceivers algorithm.
  2. Let senders be a new empty sequence.
  3. For each transceiver in transceivers,
    1. If transceiver.[[Stopped]] is false, add transceiver.[[Sender]] to senders.
  4. Return senders.
getReceivers

Returns a sequence of RTCRtpReceiver objects representing the RTP receivers that belong to non-stopped RTCRtpTransceiver objects currently attached to this RTCPeerConnection object.

When the getReceivers method is invoked, the user agent MUST run the following steps:

  1. Let transceivers be the result of executing the CollectTransceivers algorithm.
  2. Let receivers be a new empty sequence.
  3. For each transceiver in transceivers,
    1. If transceiver.[[Stopped]] is false, add transceiver.[[Receiver]] to receivers.
  4. Return receivers.
getTransceivers

Returns a sequence of RTCRtpTransceiver objects representing the RTP transceivers that are currently attached to this RTCPeerConnection object.

The getTransceivers method MUST return the result of executing the CollectTransceivers algorithm.

We define the CollectTransceivers algorithm as follows:

  1. Let transceivers be a new sequence consisting of all RTCRtpTransceiver objects in this RTCPeerConnection object's set of transceivers, in insertion order.
  2. Return transceivers.
addTrack

Adds a new track to the RTCPeerConnection, and indicates that it is contained in the specified MediaStreams.

When the addTrack method is invoked, the user agent MUST run the following steps:

  1. Let connection be the RTCPeerConnection object on which this method was invoked.

  2. Let track be the MediaStreamTrack object indicated by the method's first argument.

  3. Let kind be track.kind.

  4. Let streams be a list of MediaStream objects constructed from the method's remaining arguments, or an empty list if the method was called with a single argument.

  5. If connection.[[IsClosed]] is true, throw an InvalidStateError.

  6. Let senders be the result of executing the CollectSenders algorithm. If an RTCRtpSender for track already exists in senders, throw an InvalidAccessError.

  7. The steps below describe how to determine if an existing sender can be reused. Doing so will cause future calls to createOffer and createAnswer to mark the corresponding media description as sendrecv or sendonly and add the MSID of the sender's streams, as defined in [RFC9429] (section 5.2.2. and section 5.3.2.).

    If any RTCRtpSender object in senders matches all the following criteria, let sender be that object, or null otherwise:

  8. If sender is not null, run the following steps to use that sender:

    1. Set sender.[[SenderTrack]] to track.

    2. Set sender.[[AssociatedMediaStreamIds]] to an empty set.

    3. For each stream in streams, add stream.id to [[AssociatedMediaStreamIds]] if it's not already there.

    4. Let transceiver be the RTCRtpTransceiver associated with sender.

    5. If transceiver.[[Direction]] is "recvonly", set transceiver.[[Direction]] to "sendrecv".

    6. If transceiver.[[Direction]] is "inactive", set transceiver.[[Direction]] to "sendonly".

  9. If sender is null, run the following steps:

    1. Create an RTCRtpSender with track, kind and streams, and let sender be the result.

    2. Create an RTCRtpReceiver with kind, and let receiver be the result.

    3. Create an RTCRtpTransceiver with sender, receiver and an RTCRtpTransceiverDirection value of "sendrecv", and let transceiver be the result.

    4. Add transceiver to connection's set of transceivers.

  10. A track could have contents that are inaccessible to the application. This can be due to anything that would make a track CORS cross-origin. These tracks can be supplied to the addTrack() method, and have an RTCRtpSender created for them, but content MUST NOT be transmitted. Silence (audio), black frames (video) or equivalently absent content is sent in place of track content.

    Note that this property can change over time.

  11. Update the negotiation-needed flag for connection.

  12. Return sender.

removeTrack

Stops sending media from sender. The RTCRtpSender will still appear in getSenders. Doing so will cause future calls to createOffer to mark the media description for the corresponding transceiver as "recvonly" or "inactive", as defined in [RFC9429] (section 5.2.2.).

When the other peer stops sending a track in this manner, the track is removed from any remote MediaStreams that were initially revealed in the track event, and if the MediaStreamTrack is not already muted, a mute event is fired at the track.

Note
The same effect as removeTrack() can be achieved by setting the RTCRtpTransceiver.direction attribute of the corresponding transceiver and invoking RTCRtpSender.replaceTrack(null) on the sender. One minor difference is that replaceTrack() is asynchronous and removeTrack() is synchronous.

When the removeTrack method is invoked, the user agent MUST run the following steps:

Proposed Correction 34:Make removeTrack() a no-op after transceiver.stop() (PR #2875)
  1. Let sender be the argument to removeTrack.

  2. Let connection be the RTCPeerConnection object on which the method was invoked.

  3. If connection.[[IsClosed]] is true, throw an InvalidStateError.

  4. If sender was not created by connection, throw an InvalidAccessError.

  5. Let transceiver be the RTCRtpTransceiver object corresponding to sender.

  6. If transceiver.[[Stopping]] is true, abort these steps.

  7. Let

    Let senders be the result of executing the CollectSenders algorithm.

  8. If sender is not in senders (which indicates its transceiver was stopped or removed due to setting a session description of type "rollback"), then abort these steps.

  9. If sender.[[SenderTrack]] is null, abort these steps.

  10. Set sender.[[SenderTrack]] to null.

  11. Let transceiver be the RTCRtpTransceiver object corresponding to sender.

  12. If transceiver.[[Direction]] is "sendrecv", set transceiver.[[Direction]] to "recvonly".

  13. If transceiver.[[Direction]] is "sendonly", set transceiver.[[Direction]] to "inactive".

  14. Update the negotiation-needed flag for connection.

addTransceiver

Create a new RTCRtpTransceiver and add it to the set of transceivers.

Adding a transceiver will cause future calls to createOffer to add a media description for the corresponding transceiver, as defined in [RFC9429] (section 5.2.2.).

The initial value of mid is null. Setting a session description may later change it to a non-null value.

The sendEncodings argument can be used to specify the number of offered simulcast encodings, and optionally their RIDs and encoding parameters.

When this method is invoked, the user agent MUST run the following steps:

  1. Let init be the second argument.

  2. Let streams be init.streams.

  3. Let sendEncodings be init.sendEncodings.

  4. Let direction be init.direction.

  5. If the first argument is a string, let kind be the first argument and run the following steps:

    1. If kind is neither "audio" nor "video", throw a TypeError.

    2. Let track be null.

  6. If the first argument is a MediaStreamTrack, let track be the first argument and let kind be track.kind.

  7. If connection.[[IsClosed]] is true, throw an InvalidStateError.

  8. Validate sendEncodings by running the following addTransceiver sendEncodings validation steps, where each RTCRtpEncodingParameters dictionary in it is an "encoding":

    1. Verify that each rid value in sendEncodings conforms to the grammar specified in Section 10 of [RFC8851]. If one of the RIDs does not meet these requirements, throw a TypeError.

      If any of the following conditions are met, throw a TypeError:
      • Any encoding contains a rid member whose value does not conform to the grammar requirements specified in Section 10 of [RFC8851].
      • Some but not all encodings contain a rid member.
      • Any encoding contains a rid member whose value is the same as that of a rid contained in another encoding in sendEncodings.
    2. If any encoding contains a read-only parameter other than rid, throw an InvalidAccessError.

    3. Candidate Addition 49:Add codec to RTCRtpEncodingParameters (PR #2985)

      If any encoding contains a codec member whose value does not match any codec in RTCRtpSender.getCapabilities(kind).codecs, throw an OperationError.

    4. Candidate Addition 49:Add codec to RTCRtpEncodingParameters (PR #2985)

      If the user agent does not support changing codecs without negotiation or does not support setting codecs for individual encodings, return a promise rejected with a newly created OperationError.

    5. Proposed Addition 19:Add RTCRtpEncodingParameters.maxFramerate (PR #2785)
      Proposed Correction 20:Remove RTCRtpEncodingParameters.scaleResolutionDownBy for audio (PR #2772, PR #2799)

      If kind is "audio", remove the scaleResolutionDownBy and maxFramerate members from all encodings that contain any of them.

    6. If any encoding contains a scaleResolutionDownBy member whose value is less than 1.0, throw a RangeError.

    7. Proposed Addition 19:Add RTCRtpEncodingParameters.maxFramerate (PR #2785)

      Verify that the value of each maxFramerate member in sendEncodings that is defined is greater than 0.0. If one of the maxFramerate values does not meet this requirement, throw a RangeError.

    8. Let maxN be the maximum number of total simultaneous encodings the user agent may support for this kind, at minimum 1.This should be an optimistic number since the codec to be used is not known yet.

    9. If any encoding contains a scaleResolutionDownBy member, then for each encoding without one, add a scaleResolutionDownBy member with the value 1.0.

    10. If the number of encodings stored in sendEncodings exceeds maxN, then trim sendEncodings from the tail until its length is maxN.

    11. If the scaleResolutionDownBy attribues of sendEncodings are still undefined, initialize each encoding's scaleResolutionDownBy to 2^(length of sendEncodings - encoding index - 1). This results in smaller-to-larger resolutions where the last encoding has no scaling applied to it, e.g. 4:2:1 if the length is 3.

      If kind is "video" and none of the encodings contain a scaleResolutionDownBy member, then for each encoding, add a scaleResolutionDownBy member with the value 2^(length of sendEncodings - encoding index - 1). This results in smaller-to-larger resolutions where the last encoding has no scaling applied to it, e.g. 4:2:1 if the length is 3.

    12. If the number of encodings now stored in sendEncodings is 1, then remove any rid member from the lone entry.

      Note
      Providing a single, default RTCRtpEncodingParameters in sendEncodings allows the application to subsequently set encoding parameters using setParameters, even when simulcast isn't used.
  9. Create an RTCRtpSender with track, kind, streams and sendEncodings and let sender be the result.

    If sendEncodings is set, then subsequent calls to createOffer will be configured to send multiple RTP encodings as defined in [RFC9429] (section 5.2.2. and section 5.2.1.). When setRemoteDescription is called with a corresponding remote description that is able to receive multiple RTP encodings as defined in [RFC9429] (section 3.7.), the RTCRtpSender may send multiple RTP encodings and the parameters retrieved via the transceiver's sender.getParameters() will reflect the encodings negotiated.

  10. Create an RTCRtpReceiver with kind and let receiver be the result.

  11. Create an RTCRtpTransceiver with sender, receiver and direction, and let transceiver be the result.

  12. Add transceiver to connection's set of transceivers.

  13. Update the negotiation-needed flag for connection.

  14. Return transceiver.

WebIDLdictionary RTCRtpTransceiverInit {
  RTCRtpTransceiverDirection direction = "sendrecv";
  sequence<MediaStream> streams = [];
  sequence<RTCRtpEncodingParameters> sendEncodings = [];
};

Dictionary RTCRtpTransceiverInit Members

direction of type RTCRtpTransceiverDirection, defaulting to "sendrecv"
The direction of the RTCRtpTransceiver.
streams of type sequence<MediaStream>

When the remote RTCPeerConnection's track event fires corresponding to the RTCRtpReceiver being added, these are the streams that will be put in the event.

sendEncodings of type sequence<RTCRtpEncodingParameters>

A sequence containing parameters for sending RTP encodings of media.

WebIDLenum RTCRtpTransceiverDirection {
  "sendrecv",
  "sendonly",
  "recvonly",
  "inactive",
  "stopped"
};
RTCRtpTransceiverDirection Enumeration description
Enum valueDescription
sendrecv The RTCRtpTransceiver's RTCRtpSender sender will offer to send RTP, and will send RTP if the remote peer accepts and sender.getParameters().encodings[i].active is true for any value of i. The RTCRtpTransceiver's RTCRtpReceiver will offer to receive RTP, and will receive RTP if the remote peer accepts.
sendonly The RTCRtpTransceiver's RTCRtpSender sender will offer to send RTP, and will send RTP if the remote peer accepts and sender.getParameters().encodings[i].active is true for any value of i. The RTCRtpTransceiver's RTCRtpReceiver will not offer to receive RTP, and will not receive RTP.
recvonly The RTCRtpTransceiver's RTCRtpSender will not offer to send RTP, and will not send RTP. The RTCRtpTransceiver's RTCRtpReceiver will offer to receive RTP, and will receive RTP if the remote peer accepts.
inactive The RTCRtpTransceiver's RTCRtpSender will not offer to send RTP, and will not send RTP. The RTCRtpTransceiver's RTCRtpReceiver will not offer to receive RTP, and will not receive RTP.
stopped The RTCRtpTransceiver will neither send nor receive RTP. It will generate a zero port in the offer. In answers, its RTCRtpSender will not offer to send RTP, and its RTCRtpReceiver will not offer to receive RTP. This is a terminal state.

5.1.1 Processing Remote MediaStreamTracks

An application can reject incoming media descriptions by setting the transceiver's direction to either "inactive" to turn off both directions temporarily, or to "sendonly" to reject only the incoming side. To permanently reject an m-line in a manner that makes it available for reuse, the application would need to call RTCRtpTransceiver.stop() and subsequently initiate negotiation from its end.

To process remote tracks given an RTCRtpTransceiver transceiver, direction, msids, addList, removeList, and trackEventInits, run the following steps:

  1. Set the associated remote streams with transceiver.[[Receiver]], msids, addList, and removeList.

  2. If direction is "sendrecv" or "recvonly" and transceiver.[[FiredDirection]] is neither "sendrecv" nor "recvonly", or the previous step increased the length of addList, process the addition of a remote track with transceiver and trackEventInits.

  3. If direction is "sendonly" or "inactive", set transceiver.[[Receptive]] to false.

  4. If direction is "sendonly" or "inactive", and transceiver.[[FiredDirection]] is either "sendrecv" or "recvonly", process the removal of a remote track for the media description, with transceiver and muteTracks.

  5. Set transceiver.[[FiredDirection]] to direction.

To process the addition of a remote track given an RTCRtpTransceiver transceiver and trackEventInits, run the following steps:

  1. Let receiver be transceiver.[[Receiver]].

  2. Let track be receiver.[[ReceiverTrack]].

  3. Let streams be receiver.[[AssociatedRemoteMediaStreams]].

  4. Create a new RTCTrackEventInit dictionary with receiver, track, streams and transceiver as members and add it to trackEventInits.

To process the removal of a remote track with an RTCRtpTransceiver transceiver and muteTracks, run the following steps:

  1. Let receiver be transceiver.[[Receiver]].

  2. Let track be receiver.[[ReceiverTrack]].

  3. If track.muted is false, add track to muteTracks.

To set the associated remote streams given RTCRtpReceiver receiver, msids, addList, and removeList, run the following steps:

  1. Let connection be the RTCPeerConnection object associated with receiver.

  2. For each MSID in msids, unless a MediaStream object has previously been created with that id for this connection, create a MediaStream object with that id.

  3. Let streams be a list of the MediaStream objects created for this connection with the ids corresponding to msids.

  4. Let track be receiver.[[ReceiverTrack]].

  5. For each stream in receiver.[[AssociatedRemoteMediaStreams]] that is not present in streams, add stream and track as a pair to removeList.

  6. For each stream in streams that is not present in receiver.[[AssociatedRemoteMediaStreams]], add stream and track as a pair to addList.

  7. Set receiver.[[AssociatedRemoteMediaStreams]] to streams.

5.2 RTCRtpSender Interface

The RTCRtpSender interface allows an application to control how a given MediaStreamTrack is encoded and transmitted to a remote peer. When setParameters is called on an RTCRtpSender object, the encoding is changed appropriately.

To create an RTCRtpSender with a MediaStreamTrack, track, a string, kind, a list of MediaStream objects, streams, and optionally a list of RTCRtpEncodingParameters objects, sendEncodings, run the following steps:

  1. Let sender be a new RTCRtpSender object.

  2. Let sender have a [[SenderTrack]] internal slot initialized to track.