Cullen Jennings (Cisco) · w3.org

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 Candidate Amendments.

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 proposed and candidates amendments identified since then, 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, now fully incorporated in this version of the Recommendation.

This document was published by the Web Real-Time Communications Working Group as a Recommendation using the Recommendation track. It includes candidate 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.

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.

Table of Contents

  1. Abstract
  2. Status of This Document
  3. 1. Introduction
  4. 2. Conformance
  5. 3. Terminology
  6. 4. Peer-to-peer connections
    1. 4.1 Introduction
    2. 4.2 Configuration
      1. 4.2.1 RTCConfiguration Dictionary
      2. 4.2.2 RTCIceServer Dictionary
      3. 4.2.3 RTCIceTransportPolicy Enum
      4. 4.2.4 RTCBundlePolicy Enum
      5. 4.2.5 RTCRtcpMuxPolicy Enum
      6. 4.2.6 Offer/Answer Options
    3. 4.3 State Definitions
      1. 4.3.1 RTCSignalingState Enum
      2. 4.3.2 RTCIceGatheringState Enum
      3. 4.3.3 RTCPeerConnectionState Enum
      4. 4.3.4 RTCIceConnectionState Enum
    4. 4.4 RTCPeerConnection Interface
      1. 4.4.1 Operation
        1. 4.4.1.1 Constructor
        2. 4.4.1.2 Chain an asynchronous operation
        3. 4.4.1.3 Update the connection state
        4. 4.4.1.4 Set the session description
        5. 4.4.1.5 Set the configuration
      2. 4.4.2 Interface Definition
      3. 4.4.3 Legacy Interface Extensions
        1. 4.4.3.1 Method extensions
        2. 4.4.3.2 Legacy configuration extensions
      4. 4.4.4 Garbage collection
    5. 4.5 Error Handling
      1. 4.5.1 General Principles
    6. 4.6 Session Description Model
      1. 4.6.1 RTCSdpType
      2. 4.6.2 RTCSessionDescription Class
    7. 4.7 Session Negotiation Model
      1. 4.7.1 Setting Negotiation-Needed
      2. 4.7.2 Clearing Negotiation-Needed
      3. 4.7.3 Updating the Negotiation-Needed flag
    8. 4.8 Interfaces for Interactive Connectivity Establishment
      1. 4.8.1 RTCIceCandidate Interface
        1. 4.8.1.1 candidate-attribute Grammar
        2. 4.8.1.2 RTCIceProtocol Enum
        3. 4.8.1.3 RTCIceTcpCandidateType Enum
        4. 4.8.1.4 RTCIceCandidateType Enum
        5. 4.8.1.5 RTCIceServerTransportProtocol Enum
      2. 4.8.2 RTCPeerConnectionIceEvent
      3. 4.8.3 RTCPeerConnectionIceErrorEvent
    9. 4.9 Certificate Management
      1. 4.9.1 RTCCertificateExpiration Dictionary
      2. 4.9.2 RTCCertificate Interface
  7. 5. RTP Media API
    1. 5.1 RTCPeerConnection Interface Extensions
      1. 5.1.1 Processing Remote MediaStreamTracks
    2. 5.2 RTCRtpSender Interface
      1. 5.2.1 RTCRtpParameters Dictionary
      2. 5.2.2 RTCRtpSendParameters Dictionary
      3. 5.2.3 RTCRtpReceiveParameters Dictionary
      4. 5.2.4 RTCRtpCodingParameters Dictionary
      5. 5.2.5 RTCRtpEncodingParameters Dictionary
      6. 5.2.6 RTCRtcpParameters Dictionary
      7. 5.2.7 RTCRtpHeaderExtensionParameters Dictionary
      8. 5.2.8 RTCRtpCodec Dictionary
      9. 5.2.9 RTCRtpCodecParameters Dictionary
      10. 5.2.10 RTCRtpCapabilities Dictionary
      11. 5.2.11 RTCRtpHeaderExtensionCapability Dictionary
      12. 5.2.12 RTCSetParameterOptions Dictionary
    3. 5.3 RTCRtpReceiver Interface
    4. 5.4 RTCRtpTransceiver Interface
      1. 5.4.1 Simulcast functionality
        1. 5.4.1.1 Encoding Parameter Examples
      2. 5.4.2 "Hold" functionality
    5. 5.5 RTCDtlsTransport Interface
      1. 5.5.1 RTCDtlsTransportState Enum
      2. 5.5.2 RTCDtlsFingerprint Dictionary
    6. 5.6 RTCIceTransport Interface
      1. 5.6.1 RTCIceParameters Dictionary
      2. 5.6.2 RTCIceCandidatePair Interface
      3. 5.6.3 RTCIceGathererState Enum
      4. 5.6.4 RTCIceTransportState Enum
      5. 5.6.5 RTCIceRole Enum
      6. 5.6.6 RTCIceComponent Enum
    7. 5.7 RTCTrackEvent
  8. 6. Peer-to-peer Data API
    1. 6.1 RTCPeerConnection Interface Extensions
      1. 6.1.1 RTCSctpTransport Interface
        1. 6.1.1.1 Create an instance
        2. 6.1.1.2 Update max message size
        3. 6.1.1.3 Connected procedure
      2. 6.1.2 RTCSctpTransportState Enum
    2. 6.2 RTCDataChannel
      1. 6.2.1 Creating a data channel
      2. 6.2.2 Announcing a data channel as open
      3. 6.2.3 Announcing a data channel instance
      4. 6.2.4 Closing procedure
      5. 6.2.5 Announcing a data channel as closed
      6. 6.2.6 Transfering data channel
      7. 6.2.7 Error on creating data channels
      8. 6.2.8 Receiving messages on a data channel
    3. 6.3 RTCDataChannelEvent
    4. 6.4 Garbage Collection
  9. 7. Peer-to-peer DTMF
    1. 7.1 RTCRtpSender Interface Extensions
    2. 7.2 RTCDTMFSender
    3. 7.3 canInsertDTMF algorithm
    4. 7.4 RTCDTMFToneChangeEvent
  10. 8. Statistics Model
    1. 8.1 Introduction
    2. 8.2 RTCPeerConnection Interface Extensions
    3. 8.3 RTCStatsReport Object
    4. 8.4 RTCStats Dictionary
    5. 8.5 The stats selection algorithm
    6. 8.6 Mandatory To Implement Stats
    7. 8.7 GetStats Example
  11. 9. Media Stream API Extensions for Network Use
    1. 9.1 Introduction
    2. 9.2 MediaStream
      1. 9.2.1 id
    3. 9.3 MediaStreamTrack
      1. 9.3.1 MediaTrackSupportedConstraints, MediaTrackCapabilities, MediaTrackConstraints and MediaTrackSettings
  12. 10. Examples and Call Flows
    1. 10.1 Simple Peer-to-peer Example
    2. 10.2 Advanced Peer-to-peer Example with Warm-up
    3. 10.3 Simulcast Example
    4. 10.4 Peer-to-peer Data Example
    5. 10.5 Call Flow Browser to Browser
    6. 10.6 DTMF Example
    7. 10.7 Perfect Negotiation Example
  13. 11. Error Handling
    1. 11.1 RTCError Interface
      1. 11.1.1 Constructors
      2. 11.1.2 Attributes
      3. 11.1.3 RTCErrorInit Dictionary
    2. 11.2 RTCErrorDetailType Enum
    3. 11.3 RTCErrorEvent Interface
      1. 11.3.1 Constructors
      2. 11.3.2 Attributes
    4. 11.4 RTCErrorEventInit Dictionary
      1. 11.4.1 Dictionary RTCErrorEventInit Members
  14. 12. Event summary
  15. 13. Privacy and Security Considerations
    1. 13.1 Impact on same origin policy
    2. 13.2 Revealing IP addresses
    3. 13.3 Impact on local network
    4. 13.4 Confidentiality of Communications
    5. 13.5 Persistent information exposed by WebRTC
    6. 13.6 Setting SDP from remote endpoints
  16. 14. Accessibility Considerations
  17. A. Candidate Amendments
  18. B. Acknowledgements
  19. C. References
    1. C.1 Normative references
    2. C.2 Informative references

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:

  • Connecting to remote peers using NAT-traversal technologies such as ICE, STUN, and TURN.
  • Sending the locally-produced tracks to remote peers and receiving tracks from remote peers.
  • Sending arbitrary data directly to remote peers.

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].

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.

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.

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.

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> iceServers = [];
  RTCIceTransportPolicy iceTransportPolicy = "all";
  RTCBundlePolicy bundlePolicy = "balanced";
  RTCRtcpMuxPolicy rtcpMuxPolicy = "require";
  sequence<RTCCertificate> certificates = [];
  [EnforceRange] octet iceCandidatePoolSize = 0;
};
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 [RFC9429] (section 3.5.4. and section 4.1.1.).

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;
};
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, then this attribute specifies the username to use 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.

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

An example array of RTCIceServer objects is:

Example 1

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

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.

enum 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.

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.

enum 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.

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".

enum 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.

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

dictionary RTCOfferAnswerOptions {};
dictionary RTCOfferOptions : RTCOfferAnswerOptions {
  boolean iceRestart = false;
};
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).

dictionary RTCAnswerOptions : RTCOfferAnswerOptions {};
enum 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:
enum 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.

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

enum RTCPeerConnectionState {
  "closed",
  "failed",
  "disconnected",
  "new",
  "connecting",
  "connected"
};
RTCPeerConnectionState Enumeration description
Enum valueDescription
closed [[IceConnectionState]] is "closed".
failed The previous state doesn't apply, and either [[IceConnectionState]] is "failed" or any RTCDtlsTransports are in the "failed" state.
disconnected None of the previous states apply, and [[IceConnectionState]] is "disconnected".
new None of the previous states apply, and either [[IceConnectionState]] is "new", and all RTCDtlsTransports are in the "new" or "closed" state, or there are no transports.
connected None of the previous states apply, [[IceConnectionState]] is "connected", 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 one presently referenced by the RTCPeerConnection's set of transceivers and the RTCPeerConnection's [[SctpTransport]] internal slot if not null.

enum 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.

The set of transports considered is the one presently referenced by the 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.

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

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.

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.

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.

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. 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.

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. Candidate Correction 37:Don't fail sRD(offer) over rid mismatch, just answer with unicast. (PR #2794)

    6. 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.

       
    7. 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.

    8. 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, using the codec dictionary match algorithm with ignoreLevels set to true, 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.

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

  1. Let connection be the target RTCPeerConnection object.

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

  3. If oldConfig is not null, run 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 oldConfig.certificates, fail.

    2. Let index be 0.

    3. While index is less than the 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 oldConfig.certificates at index, then fail.

      2. Increment index by 1.

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

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

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

  4. Let iceServers be configuration.iceServers.

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

  6. 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.

  7. Set the ICE Agent's ICE transports setting to the value of configuration.iceTransportPolicy. As defined in [RFC9429] (section 4.1.18.), if the new 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.

  8. Set the ICE Agent's prefetched ICE candidate pool size as defined in [RFC9429] (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 [RFC9429] (section 4.1.18.).

  9. Set the ICE Agent's ICE servers list to iceServers.

    As defined in [RFC9429] (section 4.1.18.), if a new list of servers replaces the ICE Agent's existing ICE 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 candidate pool has a nonzero size, any existing pooled candidates will be discarded, and new candidates will be gathered from the new servers.

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

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

  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 opaque path contains one or more "/" or "@"
    • 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.

    If hostAndPortURL's path, username, or password is non-null, 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. If parsedURL's query is non-null and if parsedURL's query is different from either "transport=udp" or "transport=tcp", throw a "SyntaxError" DOMException.

  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.

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.

[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);
};
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 "

Read the original on w3.org ↗