Movatterモバイル変換


[0]ホーム

URL:


W3C

WebRTC: Real-Time Communication in Browsers

W3C Recommendation

More details about this document
This version:
https://www.w3.org/TR/2025/REC-webrtc-20250313/
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 alsotranslations.

Initial Author of this Specification was Ian Hickson, Google Inc., with the following copyright statement:
© Copyright 2004-2011 Apple Computer, Inc., Mozilla Foundation, and Opera Software ASA. You are granted a license to use, reproduce and create derivative works of this document. All subsequent changes since 26 July 2011 done by the W3C WebRTC Working Group are under the followingCopyright:
Copyright © 2011-2025World Wide Web Consortium.W3C®liability,trademark andpermissive document license rules apply.


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 currentW3C publications and the latest revision of this technical report can be found in theW3C technical reports index at https://www.w3.org/TR/.

This document includesCandidate Amendments.

Itsassociated test suite has been used to build animplementation 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 anupdated 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 theWeb Real-Time Communications Working Group as a Recommendation using theRecommendation 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.

AW3C Recommendation is a specification that, after extensive consensus-building, is endorsed byW3C and its Members, and has commitments from Working Group members toroyalty-free licensing for implementations. Future updates to this Recommendation may incorporatenew features.

Candidate additions are marked in the document.

Candidate corrections are marked in the document.

This document was produced by a group operating under theW3C Patent Policy.W3C maintains apublic 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 containsEssential Claim(s) must disclose the information in accordance withsection 6 of theW3C Patent Policy.

This document is governed by the03 November 2023W3C 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 theIETF 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 wordsMAY,MUST,MUST NOT, andSHOULD in this document are to be interpreted as described inBCP 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: theuser 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 specificationMUST 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

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

The conceptsqueue a task andnetworking task source are defined in [HTML].

The conceptfire an event is defined in [DOM].

The termsevent,event handlers andevent handler event types are defined in [HTML].

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

The termsserializable objects,serialization steps, anddeserialization steps are defined in [HTML].

The termsMediaStream,MediaStreamTrack, andMediaStreamConstraints are defined in [GETUSERMEDIA]. Note thatMediaStream is extended in9.2 MediaStream in this document whileMediaStreamTrack is extended in9.3 MediaStreamTrack in this document.

The termBlob is defined in [FILEAPI].

The termmedia description is defined in [RFC4566].

The termmedia transport is defined in [RFC7656].

The termgeneration is defined in [RFC8838] Section 2.

The termsstats object andmonitored object are defined in [WEBRTC-STATS].

When referring to exceptions, the termsthrow andcreated are defined in [WEBIDL].

The callbackVoidFunction is defined in [WEBIDL].

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

The termsfulfilled,rejected,resolved, andsettled used in the context of Promises are defined in [ECMASCRIPT-6.0].

TheAlgorithmIdentifier is defined in [WebCryptoAPI].

Note

The general principles for Javascript APIs apply, including the principle ofrun-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.

AnRTCPeerConnection instance allows an application to establish peer-to-peer communications with anotherRTCPeerConnection 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. usingWebSocket orXMLHttpRequest.

4.2 Configuration

4.2.1RTCConfiguration Dictionary

TheRTCConfiguration defines a set of parameters to configure how the peer-to-peer communication established viaRTCPeerConnection is established or re-established.

WebIDLdictionaryRTCConfiguration {sequence<RTCIceServer>iceServers = [];RTCIceTransportPolicyiceTransportPolicy = "all";RTCBundlePolicybundlePolicy = "balanced";RTCRtcpMuxPolicyrtcpMuxPolicy = "require";sequence<RTCCertificate>certificates = [];  [EnforceRange]octeticeCandidatePoolSize = 0;};
DictionaryRTCConfiguration Members
iceServers of typesequence<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 limitMUST be at least 32.

iceTransportPolicy of typeRTCIceTransportPolicy, defaulting to"all".

Indicates which candidates theICE Agent is allowed to use.

bundlePolicy of typeRTCBundlePolicy, defaulting to"balanced".

Indicates whichmedia-bundling policy to use when gathering ICE candidates.

rtcpMuxPolicy of typeRTCRtcpMuxPolicy, defaulting to"require".

Indicates whichrtcp-mux policy to use when gathering ICE candidates.

certificates of typesequence<RTCCertificate>, defaulting to[].

A set of certificates that theRTCPeerConnection uses to authenticate.

Valid values for this parameter are created through calls to thegenerateCertificate() 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. TheRTCPeerConnection 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 eachRTCPeerConnection instance.

This option allows applications to establish key continuity. AnRTCCertificate 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 typeoctet, defaulting to0

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

4.2.2RTCIceServer Dictionary

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

WebIDLdictionaryRTCIceServer {  required (DOMString orsequence<DOMString>)urls;DOMStringusername;DOMStringcredential;};
DictionaryRTCIceServer 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 typeDOMString

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

credential of typeDOMString

If thisRTCIceServer 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 ofRTCIceServer objects is:

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

4.2.3RTCIceTransportPolicy Enum

As described in[RFC9429] (section 4.1.1.), if theiceTransportPolicy member of theRTCConfiguration is specified, it defines theICE 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.

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

TheICE 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

TheICE 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 ofRTCIceCandidate.address.

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

WebIDLenumRTCBundlePolicy {"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.5RTCRtcpMuxPolicy Enum

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

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

WebIDLdictionaryRTCOfferAnswerOptions {};
DictionaryRTCOfferAnswerOptions Members
WebIDLdictionaryRTCOfferOptions :RTCOfferAnswerOptions {booleaniceRestart = false;};
DictionaryRTCOfferOptions Members
iceRestart of typeboolean, defaulting tofalse

When the value of this dictionary member istrue, or the relevantRTCPeerConnection 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 thecurrentLocalDescription 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 isfalse, and the relevantRTCPeerConnection object's[[LocalIceCredentialsToReplace]] slot is empty, and thecurrentLocalDescription attribute has valid ICE credentials, then the generated description will have the same ICE credentials as the current value from thecurrentLocalDescription attribute.

Note

Performing an ICE restart is recommended wheniceConnectionState transitions to "failed". An application may additionally choose to listen for theiceConnectionState transition to "disconnected" and then use other sources of information (such as usinggetStats 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.

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

WebIDLdictionaryRTCAnswerOptions :RTCOfferAnswerOptions {};

4.3 State Definitions

4.3.1RTCSignalingState Enum

WebIDLenumRTCSignalingState {"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 TheRTCPeerConnection has been closed; its[[IsClosed]] slot istrue.
signaling state transition diagram
Figure1 Non-normative signaling state transitions diagram. Method calls abbreviated.

An example set of transitions might be:

Caller transition:
Callee transition:

4.3.2RTCIceGatheringState Enum

WebIDLenumRTCIceGatheringState {"new","gathering","complete"};
RTCIceGatheringState Enumeration description
Enum valueDescription
new Any of theRTCIceTransports are in the "new" gathering state and none of the transports are in the "gathering" state, or there are no transports.
gathering Any of theRTCIceTransports are in the "gathering" state.
complete At least oneRTCIceTransport exists, and allRTCIceTransports are in the "complete" gathering state.

The set of transports considered is the one presently referenced by theRTCPeerConnection'sset of transceivers and theRTCPeerConnection's[[SctpTransport]] internal slot if notnull.

4.3.3RTCPeerConnectionState Enum

WebIDLenumRTCPeerConnectionState {"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 anyRTCDtlsTransports 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 allRTCDtlsTransports are in the "new" or "closed" state, or there are no transports.
connected None of the previous states apply,[[IceConnectionState]] is "connected", and allRTCDtlsTransports are in the "connected" or "closed" state.
connecting None of the previous states apply.
Note

In the "connecting" state, one or moreRTCIceTransports are in the "new" or "checking" state, or one or moreRTCDtlsTransports are in the "new" or "connecting" state.

The set of transports considered is the one presently referenced by theRTCPeerConnection'sset of transceivers and theRTCPeerConnection's[[SctpTransport]] internal slot if notnull.

4.3.4RTCIceConnectionState Enum

WebIDLenumRTCIceConnectionState {"closed","failed","disconnected","new","checking","completed","connected"};
RTCIceConnectionState Enumeration description
Enum valueDescription
closed TheRTCPeerConnection object's[[IsClosed]] slot istrue.
failed The previous state doesn't apply and anyRTCIceTransports are in the "failed" state.
disconnected None of the previous states apply and anyRTCIceTransports are in the "disconnected" state.
new None of the previous states apply and allRTCIceTransports are in the "new" or "closed" state, or there are no transports.
checking None of the previous states apply and anyRTCIceTransports are in the "new" or "checking" state.
completed None of the previous states apply and allRTCIceTransports are in the "completed" or "closed" state.
connected None of the previous states apply and allRTCIceTransports are in the "connected", "completed" or "closed" state.

The set of transports considered is the one presently referenced by theRTCPeerConnection'sset of transceivers and theRTCPeerConnection's[[SctpTransport]] internal slot if notnull.

Note that if anRTCIceTransport is discarded as a result of signaling (e.g. RTCP mux or bundling), or created as a result of signaling (e.g. adding a newmedia 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 theRTCPeerConnection operates. References to specific subsections of [RFC9429] are provided as appropriate.

4.4.1 Operation

CallingnewRTCPeerConnection(configuration) creates anRTCPeerConnection 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 serverMAY also be used as a STUN server for the purposes of gathering server reflexive candidates.

AnRTCPeerConnection 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 anRTCPeerConnection is represented by anICE agent [RFC5245]. CertainRTCPeerConnection methods involve interactions with theICE Agent, namelyaddIceCandidate,setConfiguration,setLocalDescription,setRemoteDescription andclose. These interactions are described in the relevant sections in this document and in [RFC9429]. TheICE Agent also provides indications to the user agent when the state of its internal representation of anRTCIceTransport changes, as described in5.6RTCIceTransport Interface.

The task source for the tasks listed in this section is thenetworking 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 thesetLocalDescription andsetRemoteDescription operations, and modified by theaddIceCandidate operation and thesurface 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 theunloading document cleanup steps, run the following steps:

  1. Letwindow bedocument'srelevant global object.

  2. For eachRTCPeerConnection objectconnection whoserelevant global object iswindow,close the connection withconnection and the valuetrue.

4.4.1.1 Constructor

When theRTCPeerConnection.constructor() is invoked, the user agentMUST run the following steps:

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

  2. Letconnection be a newly createdRTCPeerConnection object.

  3. Letconnection have a[[DocumentOrigin]] internal slot, initialized to therelevant settings object'sorigin.

  4. Letconfiguration be the method's first argument.
  5. If thecertificates value inconfiguration is non-empty, run the following steps for eachcertificate in certificates:

    1. If the value ofcertificate.expires is less than the current time,throw anInvalidAccessError.

    2. Ifcertificate.[[Origin]] is notsame origin withconnection.[[DocumentOrigin]],throw anInvalidAccessError.

    3. Storecertificate.

  6. Else, generate one or more newRTCCertificate instances with thisRTCPeerConnection instance and store them. ThisMAY happen asynchronously and the value ofcertificates remainsundefined 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. Initializeconnection'sICE Agent.

  8. Letconnection have a[[Configuration]] internal slot, initialized tonull.Set the configuration specified byconfiguration.

  9. Letconnection have an[[IsClosed]] internal slot, initialized tofalse.

  10. Letconnection have a[[NegotiationNeeded]] internal slot, initialized tofalse.

  11. Letconnection have an[[SctpTransport]] internal slot, initialized tonull.

  12. Letconnection have a[[DataChannels]] internal slot, initialized to an emptyordered set.

  13. Letconnection have an[[Operations]] internal slot, representing anoperations chain, initialized to an empty list.

  14. Letconnection have a[[UpdateNegotiationNeededFlagOnEmptyChain]] internal slot, initialized tofalse.

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

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

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

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

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

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

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

  22. Letconnection have a[[PendingLocalDescription]] internal slot, initialized tonull.

  23. Letconnection have a[[CurrentLocalDescription]] internal slot, initialized tonull.

  24. Letconnection have a[[PendingRemoteDescription]] internal slot, initialized tonull.

  25. Letconnection have a[[CurrentRemoteDescription]] internal slot, initialized tonull.

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

  27. Returnconnection.

4.4.1.2 Chain an asynchronous operation

AnRTCPeerConnection object has anoperations 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 notsettled, they are added to the chain and executed when all the previous calls have finished executing and their promises havesettled.

Tochain an operation to anRTCPeerConnection object'soperations chain, run the following steps:

  1. Letconnection be theRTCPeerConnection object.

  2. Ifconnection.[[IsClosed]] istrue, return a promiserejected with a newlycreatedInvalidStateError.

  3. Letoperation be the operation to be chained.

  4. Letp be a new promise.

  5. Appendoperation to[[Operations]].

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

  7. Uponfulfillment orrejection of the promise returned by theoperation, run the following steps:

    1. Ifconnection.[[IsClosed]] istrue, abort these steps.

    2. If the promise returned byoperation wasfulfilled with a value,fulfillp with that value.

    3. If the promise returned byoperation wasrejected with a value,rejectp with that value.

    4. Uponfulfillment orrejection ofp, execute the following steps:

      1. Ifconnection.[[IsClosed]] istrue, 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. Ifconnection.[[UpdateNegotiationNeededFlagOnEmptyChain]] isfalse, abort these steps.

      5. Setconnection.[[UpdateNegotiationNeededFlagOnEmptyChain]] tofalse.

      6. Update the negotiation-needed flag forconnection.

  8. Returnp.

4.4.1.3 Update the connection state

AnRTCPeerConnection object has an aggregated[[ConnectionState]]. Whenever the state of anRTCDtlsTransport changes, the user agentMUST queue a task that runs the following steps:

  1. Letconnection be thisRTCPeerConnection object associated with theRTCDtlsTransport object whose state changed.

  2. Ifconnection.[[IsClosed]] istrue, abort these steps.

  3. LetnewState be the value of deriving a new state value as described by theRTCPeerConnectionState enum.

  4. Ifconnection.[[ConnectionState]] is equal tonewState, abort these steps.

  5. Setconnection.[[ConnectionState]] tonewState.

  6. Fire an event namedconnectionstatechange atconnection.

4.4.1.4 Set the session description

To set a local session descriptiondescription on anRTCPeerConnection objectconnection,set the session descriptiondescription onconnection with the additional valuefalse.

To set a remote session descriptiondescription on anRTCPeerConnection objectconnection,set the session descriptiondescription onconnection with the additional valuetrue.

Toset a session descriptiondescription on anRTCPeerConnection objectconnection, given aremote boolean, run the following steps:

  1. Letp be a new promise.

  2. Ifdescription.type is "rollback" andconnection.[[SignalingState]] is either "stable", "have-local-pranswer", or "have-remote-pranswer", thenrejectp with a newlycreatedInvalidStateError and abort these steps.

  3. LetjsepSetOfTransceivers be a shallow copy ofconnection'sset of transceivers.

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

    1. UsejsepSetOfTransceivers 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)

      Ifremote isfalse and this triggers the ICE candidate gathering process in[RFC9429] (section 5.9.), theICE AgentMUST NOT gather candidates that would beadministratively prohibited.

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

      Ifremote istrue and this triggers ICE connectivity checks in[RFC9429] (section 5.10.), theICE AgentMUST NOT attempt to connect to candidates that areadministratively prohibited.

    4. Ifremote istrue, 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 applyingdescription leads to modifying a transceivertransceiver, andtransceiver.[[Sender]].[[SendEncodings]] is non-empty, and not equal to the encodings that would result from processingdescription, the process of applyingdescription fails. This specification does not allow remotely initiated RID renegotiation.

       
    7. If the process to applydescription fails for any reason, then the user agentMUST queue a task that runs the following steps:

      1. Ifconnection.[[IsClosed]] istrue, then abort these steps.

      2. Ifdescription.type is invalid for the currentconnection.[[SignalingState]] as described in [RFC9429] (section 5.5. andsection 5.6.), thenrejectp with a newlycreatedInvalidStateError and abort these steps.

      3. If the content ofdescription is not valid SDP syntax, thenrejectp with anRTCError (witherrorDetail set to "sdp-syntax-error" and thesdpLineNumber attribute set to the line number in the SDP where the syntax error was detected) and abort these steps.

      4. Ifremote istrue, theconnection'sRTCRtcpMuxPolicy isrequire and the description does not use RTCP mux, thenrejectp with a newlycreatedInvalidAccessError and abort these steps.

      5. If the description attempted to renegotiate RIDs, as described above, thenrejectp with a newlycreatedInvalidAccessError and abort these steps.

      6. If the content ofdescription is invalid, thenrejectp with a newlycreatedInvalidAccessError and abort these steps.

      7. For all other errors,rejectp with a newlycreatedOperationError.

    8. Ifdescription is applied successfully, the user agentMUST queue a task that runs the following steps:

      1. Ifconnection.[[IsClosed]] istrue, then abort these steps.

      2. Ifremote istrue anddescription is of type "offer", then if anyaddTrack() methods onconnection succeeded during the process to applydescription, 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 fromsetParameters methods onRTCRtpSenders associated withconnection are notsettled, abort these steps and start the process over.

      4. Ifdescription is of type "offer" andconnection.[[SignalingState]] is "stable" then for eachtransceiver inconnection'sset of transceivers, run the following steps:

        1. Settransceiver.[[Sender]].[[LastStableStateSenderTransport]] totransceiver.[[Sender]].[[SenderTransport]].

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

          Iftransceiver.[[Sender]].[[SendEncodings]].length is1 and the lone encodingcontains norid member, then settransceiver.[[Sender]].[[LastStableRidlessSendEncodings]] totransceiver.[[Sender]].[[SendEncodings]]; Otherwise, settransceiver.[[Sender]].[[LastStableRidlessSendEncodings]] tonull.

        3. Settransceiver.[[Receiver]].[[LastStableStateReceiverTransport]] totransceiver.[[Receiver]].[[ReceiverTransport]].

        4. Settransceiver.[[Receiver]].[[LastStableStateAssociatedRemoteMediaStreams]] totransceiver.[[Receiver]].[[AssociatedRemoteMediaStreams]].

        5. Settransceiver.[[Receiver]].[[LastStableStateReceiveCodecs]] totransceiver.[[Receiver]].[[ReceiveCodecs]].

      5. Ifremote isfalse, then run one of the following steps:

        1. Ifdescription is of type "offer", setconnection.[[PendingLocalDescription]] to a newRTCSessionDescription object constructed fromdescription, setconnection.[[SignalingState]] to "have-local-offer", andrelease early candidates.

        2. Ifdescription is of type "answer", then this completes an offer answer negotiation. Setconnection.[[CurrentLocalDescription]] to a newRTCSessionDescription object constructed fromdescription, and setconnection.[[CurrentRemoteDescription]] toconnection.[[PendingRemoteDescription]]. Set bothconnection.[[PendingRemoteDescription]] andconnection.[[PendingLocalDescription]] tonull. Set bothconnection.[[LastCreatedOffer]] andconnection.[[LastCreatedAnswer]] to"", setconnection.[[SignalingState]] to "stable", andrelease early candidates. Finally, if none of the ICE credentials inconnection.[[LocalIceCredentialsToReplace]] are present indescription, then setconnection.[[LocalIceCredentialsToReplace]] to an empty set.

        3. Ifdescription is of type "pranswer", then setconnection.[[PendingLocalDescription]] to a newRTCSessionDescription object constructed fromdescription, setconnection.[[SignalingState]] to "have-local-pranswer", andrelease early candidates.

      6. Otherwise, (ifremote istrue) run one of the following steps:

        1. Ifdescription is of type "offer", setconnection.[[PendingRemoteDescription]] attribute to a newRTCSessionDescription object constructed fromdescription, and setconnection.[[SignalingState]] to "have-remote-offer".

        2. Ifdescription is of type "answer", then this completes an offer answer negotiation. Setconnection.[[CurrentRemoteDescription]] to a newRTCSessionDescription object constructed fromdescription, and setconnection.[[CurrentLocalDescription]] toconnection.[[PendingLocalDescription]]. Set bothconnection.[[PendingRemoteDescription]] andconnection.[[PendingLocalDescription]] tonull. Set bothconnection.[[LastCreatedOffer]] andconnection.[[LastCreatedAnswer]] to"", and setconnection.[[SignalingState]] to "stable". Finally, if none of the ICE credentials inconnection.[[LocalIceCredentialsToReplace]] are present in the newly setconnection.[[CurrentLocalDescription]], then setconnection.[[LocalIceCredentialsToReplace]] to an empty set.

        3. Ifdescription is of type "pranswer", then setconnection.[[PendingRemoteDescription]] to a newRTCSessionDescription object constructed fromdescription and setconnection.[[SignalingState]] to "have-remote-pranswer".

      7. Ifdescription 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 ofconnection.[[SctpTransport]] tonull.

      8. LettrackEventInits,muteTracks,addList,removeList anderrorList be empty lists.

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

        1. Ifdescription 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 themax-message-size SDP attribute is updated,update the data max message size ofconnection.[[SctpTransport]].

        2. Ifdescription negotiates the DTLS role of the SCTP transport, then for eachRTCDataChannel,channel, with anullid, run the following step:

          1. Givechannel a new ID generated according to [RFC8832]. If no available ID could be generated, setchannel.[[ReadyState]] to "closed", and addchannnel toerrorList.
      10. Ifdescription is not of type "rollback", then run the following steps:

        1. Ifremote isfalse, then run the following steps for eachmedia description indescription:

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

            1. Lettransceiver be theRTCRtpTransceiver used to create themedia description.

            2. Settransceiver.[[Mid]] totransceiver.[[JsepMid]].

            3. Iftransceiver.[[Stopped]] istrue, abort these sub steps.

            4. If themedia description is indicated as using an existingmediamediatransport according to [RFC8843], lettransport be theRTCDtlsTransport object representing the RTP/RTCP component of that transport.

            5. Otherwise, lettransport be a newly createdRTCDtlsTransport object with a new underlyingRTCIceTransport.

            6. Settransceiver.[[Sender]].[[SenderTransport]] totransport.

            7. Settransceiver.[[Receiver]].[[ReceiverTransport]] totransport.

          2. Lettransceiver be theRTCRtpTransceiverassociated with themedia description.

          3. Iftransceiver.[[Stopped]] istrue, abort these sub steps.

          4. Letdirection be anRTCRtpTransceiverDirection value representing the direction from themediamediadescription.

          5. Ifdirection is "sendrecv" or "recvonly", settransceiver.[[Receptive]] totrue, otherwise set it tofalse.

          6. Settransceiver.[[Receiver]].[[ReceiveCodecs]] to the codecs thatdescription negotiates for receiving and which the user agent is currently prepared to receive.

            Note

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

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

            1. Iftransceiver.[[Sender]].[[SendEncodings]] .length is greater than1, then run the following steps:

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

              2. Ifdescription is missing any of the previously negotiated layers, then remove the dictionaries that correspond to the missing layers fromtransceiver.[[Sender]].[[SendEncodings]].

            2. Settransceiver.[[Sender]].[[SendCodecs]] to the codecs thatdescription negotiates for sending and which the user agent is currently capable of sending, and settransceiver.[[Sender]].[[LastReturnedParameters]] tonull.

            3. Ifdirection is "sendonly" or "inactive", andtransceiver.[[FiredDirection]] is either "sendrecv" or "recvonly", then run the following steps:

              1. Set the associated remote streams giventransceiver.[[Receiver]], an empty list, another empty list, andremoveList.

              2. process the removal of aremoteremotetrack for themedia description, giventransceiver andmuteTracks.

            4. Settransceiver.[[CurrentDirection]] andtransceiver.[[FiredDirection]] todirection.

        2. Otherwise, (ifremote istrue) run the following steps for eachmedia description indescription:

          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 thedescription is of type "offer" andthemedia descriptioncontains a request to receive simulcast, use the order of the rid values specified in the simulcast attribute to create anRTCRtpEncodingParameters dictionary for each of the simulcast layers, populating therid member according to the corresponding ridvaluevalue (using only the first value if comma-separated alternatives exist), and letsendEncodingsproposedSendEncodings bethe listthe listcontaining the created dictionaries. Otherwise, letsendEncodingsproposedSendEncodingsbeananempty list.

          2. For each encoding,encoding, inproposedSendEncodings in reverse order, ifencoding'srid matches that of another encoding inproposedSendEncodings, removeencoding fromproposedSendEncodings.

          3. LetsupportedEncodings be the maximum number of encodings that the implementation can support. If the length ofsendEncodingsproposedSendEncodings is greater thansupportedEncodings, truncatesendEncodingsproposedSendEncodings so that its length issupportedEncodings.
          4. IfsendEncodingsproposedSendEncodings is non-empty, set seteach encoding'sscaleResolutionDownBy to2^(length ofsendEncodingsproposedSendEncodings - encoding index - 1).
          5. As described by[RFC8829RFC9429] (section 5.10.), attempt to find an existingRTCRtpTransceiver object,transceiver, to represent themedia description.

          6. If a suitable transceiver was found (transceiver is set), andsendEncodingsproposedSendEncodings is non-empty, settransceiver.[[Sender]].[[SendEncodings]]tosendEncodings, and settransceiver.[[Sender]].[[LastReturnedParameters]] tonull.run the following steps:

            1. If the length oftransceiver.[[Sender]].[[SendEncodings]] is1, and the lone encodingcontains norid member, settransceiver.[[Sender]].[[SendEncodings]] toproposedSendEncodings, and settransceiver.[[Sender]].[[LastReturnedParameters]] tonull.

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

            1. Create an RTCRtpSender,sender, from themediamediadescription usingsendEncodingsproposedSendEncodings.

            2. Create an RTCRtpReceiver,receiver, from themediamediadescription.

            3. Create an RTCRtpTransceiver withsender,receiver and anRTCRtpTransceiverDirection value of "recvonly", and lettransceiver be the result.

            4. Addtransceiver to theconnection'ssetofoftransceivers.

          8. Ifdescription is of type "answer" or "pranswer", andtransceiver.[[Sender]].[[SendEncodings]] .length is greater than1, then run the following steps:

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

            2. Ifdescriptionrejectsis missingany of theofferedpreviously negotiatedlayers,thenthenremovethethedictionaries that correspondto rejectedto the missinglayers fromtransceiver.[[Sender]].[[SendEncodings]].

            3. Update the paused status as indicated by [RFC8853] of each simulcast layer by setting theactive member on the corresponding dictionaries intransceiver.[[Sender]].[[SendEncodings]] totrue for unpaused or tofalse for paused.

          9. Settransceiver.[[Mid]] totransceiver.[[JsepMid]].

          10. Letdirection be anRTCRtpTransceiverDirection value representing the direction from themediamediadescription, but with the send and receive directions reversed to represent this peer's point of view. If themedia description is rejected, setdirection to "inactive".

          11. Ifdirection is "sendrecv" or "recvonly", letmsids be a list of the MSIDs that the media description indicatestransceiver.[[Receiver]].[[ReceiverTrack]] is to be associated with. Otherwise, letmsids be an empty list.

            Note
            msids will be an empty list here ifmedia description is rejected.
          12. Process remote tracks withtransceiver,direction,msids,addList,removeList, andtrackEventInits.

          13. Settransceiver.[[Receiver]].[[ReceiveCodecs]] to the codecs thatdescription negotiates for receiving and which the user agent is currently prepared to receive.

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

            1. Settransceiver.[[Sender]].[[SendCodecs]] to the codecs thatdescription negotiates for sending and which the user agent is currently capable of sending.

            2. Settransceiver.[[CurrentDirection]]andtransceiver.[[Direction]]stodirection.

            3. Lettransport be theRTCDtlsTransport object representing the RTP/RTCP component of themediamediatransport used bytransceiver'sassociatedmedia description, according to [RFC8843].

            4. Settransceiver.[[Sender]].[[SenderTransport]] totransport.

            5. Settransceiver.[[Receiver]].[[ReceiverTransport]] totransport.

            6. Set the[[IceRole]] oftransport 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 themedia description is rejected, andtransceiver.[[Stopped]] isfalse, thenstopthetheRTCRtpTransceivertransceiver.

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

        1. LetpendingDescription be eitherconnection.[[PendingLocalDescription]] orconnection.[[PendingRemoteDescription]], whichever one is notnull.

        2. For eachtransceiver in theconnection'sset of transceivers run the following steps:

          1. Iftransceiver was notassociated with amedia description prior topendingDescription being set, disassociate it and set bothtransceiver.[[JsepMid]] andtransceiver.[[Mid]] tonull.

          2. Settransceiver.[[Sender]].[[SenderTransport]] totransceiver.[[Sender]].[[LastStableStateSenderTransport]].

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

            Iftransceiver.[[Sender]].[[LastStableRidlessSendEncodings]] is notnull, and any encoding intransceiver.[[Sender]].[[SendEncodings]]contains arid member, then settransceiver.[[Sender]].[[SendEncodings]] totransceiver.[[Sender]].[[LastStableRidlessSendEncodings]].

          4. Settransceiver.[[Receiver]].[[ReceiverTransport]] totransceiver.[[Receiver]].[[LastStableStateReceiverTransport]].

          5. Settransceiver.[[Receiver]].[[ReceiveCodecs]] totransceiver.[[Receiver]].[[LastStableStateReceiveCodecs]].

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

            1. Letmsids be a list of theids of allMediaStream objects intransceiver.[[Receiver]].[[LastStableStateAssociatedRemoteMediaStreams]], or an empty list if there are none.

            2. Process remote tracks withtransceiver,transceiver.[[CurrentDirection]],msids,addList,removeList, andtrackEventInits.

          7. Iftransceiver was created whenpendingDescription was set, and a track has never been attached to it viaaddTrack(), thenstop the RTCRtpTransceivertransceiver, and remove it fromconnection'sset of transceivers.

        3. Setconnection.[[PendingLocalDescription]] andconnection.[[PendingRemoteDescription]] tonull, and setconnection.[[SignalingState]] to "stable".

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

        1. For eachtransceiver in theconnection'sset of transceivers run the following steps:

          1. Iftransceiver isstopped,associated with an m= section and the associated m= section is rejected inconnection.[[CurrentLocalDescription]] orconnection.[[CurrentRemoteDescription]], remove thetransceiver from theconnection'sset of transceivers.

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

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

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

          For eachtransceiver inconnection'sset of transceivers:

          1. Letcodecs betransceiver.[[Sender]].[[SendCodecs]].

          2. Ifcodecs is not an empty list:

            1. For eachencoding intransceiver.[[Sender]].[[SendEncodings]], ifencoding.codec does not match any entry incodecs, using thecodec dictionary match algorithm withignoreLevels set totrue,removeencoding.codec.

        3. Clear the negotiation-needed flag andupdate the negotiation-needed flag.

      14. Ifconnection.[[SignalingState]] changed above,fire an event namedsignalingstatechange atconnection.

      15. For eachchannel inerrorList,fire an event namederror using theRTCErrorEvent interface with theerrorDetail attribute set to "data-channel-failure" atchannel.

      16. For eachtrack inmuteTracks,set the muted state oftrack to the valuetrue.

      17. For eachstream andtrack pair inremoveList,remove the tracktrack fromstream.

      18. For eachstream andtrack pair inaddList,add the tracktrack tostream.

      19. For each entryentry intrackEventInits,fire an event namedtrack using theRTCTrackEvent interface with itsreceiver attribute initialized toentry.receiver, itstrack attribute initialized toentry.track, itsstreams attribute initialized toentry.streams and itstransceiver attribute initialized toentry.transceiver at theconnection object.

      20. Resolvep withundefined.

  5. Returnp.

4.4.1.5 Set the configuration

Toset a configuration withconfiguration, run the following steps:

  1. Letconnection be the targetRTCPeerConnection object.

  2. LetoldConfig beconnection.[[Configuration]].

  3. IfoldConfig is notnull, run the following steps, and if any of them fail,throw anInvalidModificationError:

    1. If the length ofconfiguration.certificates is different from the length ofoldConfig.certificates, fail.

    2. Letindex be 0.

    3. Whileindex is less than the length ofconfiguration.certificates, run the following steps:

      1. If the ECMAScript object represented by the value ofconfiguration.certificates atindex is not the same as the ECMAScript object represented by the value ofoldConfig.certificates atindex, then fail.

      2. Incrementindex by 1.

    4. If the value ofconfiguration.bundlePolicy differs fromoldConfig.bundlePolicy, then fail.

    5. If the value ofconfiguration.rtcpMuxPolicy differs fromoldConfig.rtcpMuxPolicy, then fail.

    6. If the value ofconfiguration.iceCandidatePoolSize differs fromoldConfig.iceCandidatePoolSize, andsetLocalDescription has already been called, then fail.

  4. LeticeServers beconfiguration.iceServers.

  5. TruncateiceServers to the maximum number of supported elements.

  6. For eachserver iniceServers, run the following steps:

    1. Leturls beserver.urls.

    2. Ifurls is a string, seturls to a list consisting of just that string.

    3. Ifurls is empty,throw a "SyntaxError"DOMException.

    4. For eachurl inurls, run thevalidate an ICE server URL algorithm onurl.

  7. Set theICE Agent'sICE transports setting to the value ofconfiguration.iceTransportPolicy. As defined in[RFC9429] (section 4.1.18.), if the newICE 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 theICE Agent's prefetchedICE candidate pool size as defined in[RFC9429] (section 3.5.4. andsection 4.1.1.) to the value ofconfiguration.iceCandidatePoolSize. If the newICE 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 theICE Agent'sICE servers list toiceServers.

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

  10. Storeconfiguration in the[[Configuration]] internal slot.

Tovalidate an ICE server URLurl, run the following steps:

Candidate Correction 33:Use the url spec to parse ice server urls (PR #2853,PR #2996,PR #2998)
  1. Parse theurl using the generic URI syntax defined in [RFC3986] and obtain thescheme name. If the parsing based on the syntax defined in [RFC3986] fails,throw aSyntaxError. If thescheme name is not implemented by the browserthrow aNotSupportedError. Ifscheme name isturn orturns, and parsing theurl using the syntax defined in [RFC7065] fails,throw aSyntaxError. Ifscheme name isstun orstuns, and parsing theurl using the syntax defined in [RFC7064] fails,throw aSyntaxError.

  2. LetparsedURL be the result ofparsingurl.

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

    • parsedURL is failure
    • parsedURL'sscheme is neither"stun","stuns","turn", nor"turns"
    • parsedURL does not have anopaque path
    • parsedURL'sopaque path contains one or more"/" or"@"
    • parsedURL'sfragment is non-null
    • parsedURL'sscheme is"stun" or"stuns", andparsedURL'squery is non-null
  4. IfparsedURL'sscheme is not implemented by the user agent, thenthrow aNotSupportedError.

  5. LethostAndPortURL be result ofparsing the concatenation of"https://" andparsedURL'spath.

  6. IfhostAndPortURL is failure, thenthrow a "SyntaxError"DOMException.

    IfhostAndPortURL'spath,username, orpassword is non-null, thenthrow 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. IfparsedURL'squery is non-null and ifparsedURL'squery is different from either"transport=udp" or"transport=tcp",throw a "SyntaxError"DOMException.

  8. Ifscheme nameparsedURL's'scheme isturn"turn"orturnsor"turns", and either ofserver.username orserver.credentialare omitteddonot exist, thenthrow anInvalidAccessError.

  9. Ifscheme name isturn orturns, andserver.credentialType is "password", andserver.credential is not aDOMString, thenthrow anInvalidAccessError.

4.4.2 Interface Definition

TheRTCPeerConnection interface presented in this section is extended by several partial interfaces throughout this specification. Notably, theRTP Media API section, which adds the APIs to send and receiveMediaStreamTrack objects.

WebIDL[Exposed=Window]interfaceRTCPeerConnection :EventTarget  {constructor(optionalRTCConfigurationconfiguration = {});Promise<RTCSessionDescriptionInit>createOffer(optionalRTCOfferOptionsoptions = {});Promise<RTCSessionDescriptionInit>createAnswer(optionalRTCAnswerOptionsoptions = {});Promise<undefined>setLocalDescription(optionalRTCLocalSessionDescriptionInitdescription = {});  readonly attributeRTCSessionDescription?localDescription;  readonly attributeRTCSessionDescription?currentLocalDescription;  readonly attributeRTCSessionDescription?pendingLocalDescription;Promise<undefined>setRemoteDescription(RTCSessionDescriptionInitdescription);  readonly attributeRTCSessionDescription?remoteDescription;  readonly attributeRTCSessionDescription?currentRemoteDescription;  readonly attributeRTCSessionDescription?pendingRemoteDescription;Promise<undefined>addIceCandidate(optionalRTCIceCandidateInitcandidate = {});  readonly attributeRTCSignalingStatesignalingState;  readonly attributeRTCIceGatheringStateiceGatheringState;  readonly attributeRTCIceConnectionStateiceConnectionState;  readonly attributeRTCPeerConnectionStateconnectionState;  readonly attributeboolean?canTrickleIceCandidates;undefinedrestartIce();RTCConfigurationgetConfiguration();undefinedsetConfiguration(optionalRTCConfigurationconfiguration = {});undefinedclose();  attributeEventHandleronnegotiationneeded;  attributeEventHandleronicecandidate;  attributeEventHandleronicecandidateerror;  attributeEventHandleronsignalingstatechange;  attributeEventHandleroniceconnectionstatechange;  attributeEventHandleronicegatheringstatechange;  attributeEventHandleronconnectionstatechange;  // 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(RTCSessionDescriptionCallbacksuccessCallback,RTCPeerConnectionErrorCallbackfailureCallback,                            optionalRTCOfferOptionsoptions = {});Promise<undefined>setLocalDescription(RTCLocalSessionDescriptionInitdescription,VoidFunctionsuccessCallback,RTCPeerConnectionErrorCallbackfailureCallback);Promise<undefined>createAnswer(RTCSessionDescriptionCallbacksuccessCallback,RTCPeerConnectionErrorCallbackfailureCallback);Promise<undefined>setRemoteDescription(RTCSessionDescriptionInitdescription,VoidFunctionsuccessCallback,RTCPeerConnectionErrorCallbackfailureCallback);Promise<undefined>addIceCandidate(RTCIceCandidateInitcandidate,VoidFunctionsuccessCallback,RTCPeerConnectionErrorCallbackfailureCallback);};
Attributes
localDescription of typeRTCSessionDescription, readonly, nullable

ThelocalDescription attributeMUST return[[PendingLocalDescription]] if it is notnull and otherwise itMUST return[[CurrentLocalDescription]].

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

currentLocalDescription of typeRTCSessionDescription, readonly, nullable

ThecurrentLocalDescription attributeMUST return[[CurrentLocalDescription]].

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

pendingLocalDescription of typeRTCSessionDescription, readonly, nullable

ThependingLocalDescription attributeMUST return[[PendingLocalDescription]].

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

remoteDescription of typeRTCSessionDescription, readonly, nullable

TheremoteDescription attributeMUST return[[PendingRemoteDescription]] if it is notnull and otherwise itMUST return[[CurrentRemoteDescription]].

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

currentRemoteDescription of typeRTCSessionDescription, readonly, nullable

ThecurrentRemoteDescription attributeMUST return[[CurrentRemoteDescription]].

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

pendingRemoteDescription of typeRTCSessionDescription, readonly, nullable

ThependingRemoteDescription attributeMUST return[[PendingRemoteDescription]].

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

signalingState of typeRTCSignalingState, readonly

ThesignalingState attributeMUST return theRTCPeerConnection object's[[SignalingState]].

iceGatheringState of typeRTCIceGatheringState, readonly

TheiceGatheringState attributeMUST return theRTCPeerConnection object's[[IceGatheringState]].

iceConnectionState of typeRTCIceConnectionState, readonly

TheiceConnectionState attributeMUST return theRTCPeerConnection object's[[IceConnectionState]].

connectionState of typeRTCPeerConnectionState, readonly

TheconnectionState attributeMUST return theRTCPeerConnection object's[[ConnectionState]].

canTrickleIceCandidates of typeboolean, readonly, nullable

ThecanTrickleIceCandidates 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 ofsetRemoteDescription, this value isnull.

onnegotiationneeded of typeEventHandler
The event type of this event handler isnegotiationneeded.
onicecandidate of typeEventHandler
The event type of this event handler isicecandidate.
onicecandidateerror of typeEventHandler
The event type of this event handler isicecandidateerror.
onsignalingstatechange of typeEventHandler
The event type of this event handler issignalingstatechange.
oniceconnectionstatechange of typeEventHandler
The event type of this event handler isiceconnectionstatechange
onicegatheringstatechange of typeEventHandler
The event type of this event handler isicegatheringstatechange.
onconnectionstatechange of typeEventHandler
The event type of this event handler isconnectionstatechange.
Methods
createOffer

ThecreateOffer method generates a blob of SDP that contains an RFC 3264 offer with the supported configurations for the session, including descriptions of the localMediaStreamTracks attached to thisRTCPeerConnection, the codec/RTP/RTCP capabilities supported by this implementation, and parameters of theICE agent and the DTLS connection. Theoptions 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 thatsetLocalDescription will succeed when it attempts to acquire those resources. The session descriptionsMUST remain usable bysetLocalDescription without causing an error until at least the end of thefulfillment callback of the returned promise.

Creating the SDPMUST follow the appropriate process for generating an offer described in [RFC9429], except the user agentMUST treat astopping transceiver asstopped 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 eventcreateOffer 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 theICE agent'susernameFragment,password and ICE options (as defined in [RFC5245], Section 14) and may also contain any local candidates that have been gathered by the agent.

Thecertificates value inconfiguration for theRTCPeerConnection provides the certificates configured by the application for theRTCPeerConnection. 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 agentMUST run the following steps:

  1. Letconnection be theRTCPeerConnection object on which the method was invoked.

  2. Ifconnection.[[IsClosed]] istrue, return a promiserejected with a newlycreatedInvalidStateError.

  3. Return the result ofchaining the result ofcreating an offer withconnection toconnection'soperations chain.

Tocreate an offer givenconnection run the following steps:

  1. Ifconnection.[[SignalingState]] is neither "stable" nor "have-local-offer", return a promiserejected with a newlycreatedInvalidStateError.

  2. Letp be a new promise.

  3. In parallel, begin thein-parallel steps to create an offer givenconnection andp.

  4. Returnp.

Thein-parallel steps to create an offer givenconnection and a promisep are as follows:

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

  2. Inspect theofferer'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,rejectp with a newlycreatedOperationError and abort these steps.

  4. Queue a task that runs thefinal steps to create an offer givenconnection andp.

Thefinal steps to create an offer givenconnection and a promisep are as follows:

  1. Ifconnection.[[IsClosed]] istrue, then abort these steps.

  2. Ifconnection was modified in such a way that additional inspection of theofferer's system state is necessary, thenin parallel begin thein-parallel steps to create an offer again, givenconnection andp, and abort these steps.

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

    1. As described in [RFC8843] (Section 7), if bundling is used (seeRTCBundlePolicy) an offerer tagged m= section must be selected in order to negotiate a BUNDLE group. The user agentMUST choose the m= section that corresponds to the first non-stopped transceiver in theset 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. LetfilteredCodecs be the result of applying the following filter ontransceiver.[[PreferredCodecs]]. The filteringMUST NOT change the order of the codec preferences:

      1. Letkind betransceiver's[[Receiver]]'s[[ReceiverTrack]]'skind.

      2. Iftransceiver.direction is "sendonly" or "sendrecv", exclude any codecs not included in thelist of implemented send codecs forkind, using thecodec dictionary match algorithm withignoreLevels set totrue.

      3. Iftransceiver.direction is "recvonly" or "sendrecv", exclude any codecs not included in thelist of implemented receive codecs forkind, using thecodec dictionary match algorithm withignoreLevels set totrue.

      Thecodec preferences of amedia description'sassociated transceiver,transceiver, is said to be the value offilteredCodecs if non-empty and said to be unset otherwise.

    3. If the length of the[[SendEncodings]] slot of theRTCRtpSender is larger than 1, then for each encoding given in[[SendEncodings]] of theRTCRtpSender, add ana=rid send line to the corresponding media section, and add ana=simulcast:send line giving the RIDs in the same order as given in theencodings 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. Letoffer be a newly createdRTCSessionDescriptionInit dictionary with itstype member initialized to the string "offer" and itssdp member initialized tosdpString.

  5. Set the[[LastCreatedOffer]] internal slot tosdpString.

  6. Resolvep withoffer.

createAnswer

ThecreateAnswer method generates an [SDP] answer with the supported configuration for the session that is compatible with the parameters in the remote configuration. LikecreateOffer, the returned blob of SDP contains descriptions of the localMediaStreamTracks attached to thisRTCPeerConnection, the codec/RTP/RTCP options negotiated for this session, and any candidates that have been gathered by theICE Agent. Theoptions parameter may be supplied to provide additional control over the generated answer.

LikecreateOffer, the returned descriptionSHOULD reflect the current state of the system. The session descriptionsMUST remain usable bysetLocalDescription without causing an error until at least the end of thefulfillment 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 SDPMUST follow the appropriate process for generating an answer described in [RFC9429].

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

Thecertificates value inconfiguration for theRTCPeerConnection provides the certificates configured by the application for theRTCPeerConnection. 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 thetype to "pranswer".

When the method is called, the user agentMUST run the following steps:

  1. Letconnection be theRTCPeerConnection object on which the method was invoked.

  2. Ifconnection.[[IsClosed]] istrue, return a promiserejected with a newlycreatedInvalidStateError.

  3. Return the result ofchaining the result ofcreating an answer withconnection toconnection'soperations chain.

Tocreate an answer givenconnection run the following steps:

  1. Ifconnection.[[SignalingState]] is neither "have-remote-offer" nor "have-local-pranswer", return a promiserejected with a newlycreatedInvalidStateError.

  2. Letp be a new promise.

  3. In parallel, begin thein-parallel steps to create an answer givenconnection andp.

  4. Returnp.

Thein-parallel steps to create an answer givenconnection and a promisep are as follows:

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

  2. Inspect theanswerer'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,rejectp with a newlycreatedOperationError and abort these steps.

  4. Queue a task that runs thefinal steps to create an answer givenp.

Thefinal steps to create an answer given a promisep are as follows:

  1. Ifconnection.[[IsClosed]] istrue, then abort these steps.

  2. Ifconnection was modified in such a way that additional inspection of theanswerer's system state is necessary, thenin parallel begin thein-parallel steps to create an answer again givenconnection andp, and abort these steps.

    Note
    This may be necessary if, for example,createAnswer was called when anRTCRtpTransceiver's direction was "recvonly", but while performing thein-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 ofconnection and itsRTCRtpTransceivers, 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. Thecodec preferences of an m= section's associated transceiver is said to be the value of theRTCRtpTransceiver.[[PreferredCodecs]] with the following filtering applied (or said not to be set if[[PreferredCodecs]] is empty):

      1. If thedirection is "sendrecv", exclude any codecs not included in the intersection ofRTCRtpSender.getCapabilities(kind).codecs andRTCRtpReceiver.getCapabilities(kind).codecs.

      2. If thedirection is "sendonly", exclude any codecs not included inRTCRtpSender.getCapabilities(kind).codecs.

      3. If thedirection is "recvonly", exclude any codecs not included inRTCRtpReceiver.getCapabilities(kind).codecs.

      The filteringMUST NOT change the order of the codec preferences.

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

    3. LetfilteredCodecs be the result of applying the following filter ontransceiver.[[PreferredCodecs]]. The filteringMUST NOT change the order of the codec preferences:

      1. Letkind betransceiver's[[Receiver]]'s[[ReceiverTrack]]'skind.

      2. Iftransceiver.direction is "sendonly" or "sendrecv", exclude any codecs not included in thelist of implemented send codecs forkind, using thecodec dictionary match algorithm withignoreLevels set totrue.

      3. Iftransceiver.direction is "recvonly" or "sendrecv", exclude any codecs not included in thelist of implemented receive codecs forkind, using thecodec dictionary match algorithm withignoreLevels set totrue.

      Thecodec preferences of amedia description'sassociated transceiver,transceiver, is said to be the value offilteredCodecs if non-empty and said to be unset otherwise.

    4. 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 thea=simulcast attribute contains comma-separated alternatives for RIDs, remove all but the first ones.

      2. If there are any identically named RIDs in thea=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 asetRemoteDescription(offer) establishes a sender'sproposed envelope, the sender's[[SendEncodings]] is updated in "have-remote-offer", exposing it to rollback. However, once asimulcast envelope has been established for the sender, subsequent pruning of the sender's[[SendEncodings]] happen when this answer is set withsetLocalDescription.

  4. Letanswer be a newly createdRTCSessionDescriptionInit dictionary with itstype member initialized to the string "answer" and itssdp member initialized tosdpString.

  5. Set the[[LastCreatedAnswer]] internal slot tosdpString.

  6. Resolvep withanswer.

setLocalDescription

ThesetLocalDescription method instructs theRTCPeerConnection to apply the suppliedRTCLocalSessionDescriptionInit 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, theRTCPeerConnectionMUST 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 theRTCPeerConnection 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, thensetLocalDescription will implicitlycreate an offer orcreate 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 eithercreateOffer orcreateAnswer.

When the method is invoked, the user agentMUST run the following steps:

  1. Letdescription be the method's first argument.

  2. Letconnection be theRTCPeerConnection object on which the method was invoked.

  3. Letsdp bedescription.sdp.

  4. Return the result ofchaining the following steps toconnection'soperations chain:

    1. Lettype bedescription.type if present, or "offer" if not present andconnection.[[SignalingState]] is either "stable", "have-local-offer", or "have-remote-pranswer"; otherwise "answer".

    2. Iftype is "offer", andsdp is not the empty string and not equal toconnection.[[LastCreatedOffer]], then return a promiserejected with a newlycreatedInvalidModificationError and abort these steps.

    3. Iftype is "answer" or "pranswer", andsdp is not the empty string and not equal toconnection.[[LastCreatedAnswer]], then return a promiserejected with a newlycreatedInvalidModificationError and abort these steps.

    4. Ifsdp is the empty string, andtype is "offer", then run the following sub steps:

      1. Setsdp to the value ofconnection.[[LastCreatedOffer]].

      2. Ifsdp is the empty string, or if it no longer accurately represents theofferer's system state ofconnection, then letp be the result ofcreating an offer withconnection, and return the result ofreacting top with a fulfillment step thatsets the local session description indicated by its first argument.

    5. Ifsdp is the empty string, andtype is "answer" or "pranswer", then run the following sub steps:

      1. Setsdp to the value ofconnection.[[LastCreatedAnswer]].

      2. Ifsdp is the empty string, or if it no longer accurately represents theanswerer's system state ofconnection, then letp be the result ofcreating an answer withconnection, and return the result ofreacting top with the following fulfillment steps:

        1. Letanswer be the first argument to these fulfillment steps.

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

    6. Return the result ofsetting 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 theICE Agent.

setRemoteDescription

ThesetRemoteDescription method instructs theRTCPeerConnection to apply the suppliedRTCSessionDescriptionInit as the remote offer or answer. This API changes the local media state.

When the method is invoked, the user agentMUST run the following steps:

  1. Letdescription be the method's first argument.

  2. Letconnection be theRTCPeerConnection object on which the method was invoked.

  3. Return the result ofchaining the following steps toconnection'soperations chain:

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

      1. Letp be the result ofsetting the local session description indicated by{type: "rollback"}.

      2. Return the result ofreacting top with a fulfillment step thatsets the remote session descriptiondescription, and abort these steps.

    2. Return the result ofsetting the remote session descriptiondescription.

addIceCandidate

TheaddIceCandidate method provides a remote candidate to theICE Agent. This method can also be used to indicate the end of remote candidates when called with an empty string for thecandidate member. The only members of the argument used by this method arecandidate,sdpMid,sdpMLineIndex, andusernameFragment; the rest are ignored. When the method is invoked, the user agentMUST run the following steps:

  1. Letcandidate be the method's argument.

  2. Letconnection be theRTCPeerConnection object on which the method was invoked.

  3. Ifcandidate.candidate is not an empty string and bothcandidate.sdpMid andcandidate.sdpMLineIndex arenull, return a promiserejected with a newlycreatedTypeError.

  4. Return the result ofchaining the following steps toconnection'soperations chain:

    1. IfremoteDescription isnull return a promiserejected with a newlycreatedInvalidStateError.

    2. Ifcandidate.sdpMid is notnull, run the following steps:

      1. Ifcandidate.sdpMid is not equal to the mid of any media description inremoteDescription, return a promiserejected with a newlycreatedOperationError.

    3. Else, ifcandidate.sdpMLineIndex is notnull, run the following steps:

      1. Ifcandidate.sdpMLineIndex is equal to or larger than the number of media descriptions inremoteDescription, return a promiserejected with a newlycreatedOperationError.

    4. If eithercandidate.sdpMid orcandidate.sdpMLineIndex indicate a media description inremoteDescription whose associated transceiver isstopped, return a promiseresolved withundefined.

    5. Ifcandidate.usernameFragment is notnull, and is not equal to any username fragment present in the correspondingmedia description of an applied remote description, return a promiserejected with a newlycreatedOperationError.

    6. Letp be a new promise.

    7. In parallel, if the candidate is notadministratively prohibited, add the ICE candidatecandidate as described in[RFC9429] (section 4.1.19.). Usecandidate.usernameFragment to identify the ICEgeneration; ifusernameFragment isnull, process thecandidate for the most recent ICEgeneration.

      Ifcandidate.candidate is an empty string, processcandidate as an end-of-candidates indication for the correspondingmedia description and ICE candidategeneration. If bothcandidate.sdpMid andcandidate.sdpMLineIndex arenull, then this end-of-candidates indication applies to allmedia descriptions.

      1. Ifcandidate could not be successfully added the user agentMUST queue a task that runs the following steps:

        1. Ifconnection.[[IsClosed]] istrue, then abort these steps.

        2. Rejectp with a newlycreatedOperationError and abort these steps.

      2. Ifcandidate is applied successfully, or if the candidate wasadministratively prohibited the user agentMUST queue a task that runs the following steps:

        1. Ifconnection.[[IsClosed]] istrue, then abort these steps.

        2. Ifconnection.[[PendingRemoteDescription]] is notnull, and represents the ICEgeneration for whichcandidate was processed, addcandidate toconnection.[[PendingRemoteDescription]].sdp.

        3. Ifconnection.[[CurrentRemoteDescription]] is notnull, and represents the ICEgeneration for whichcandidate was processed, addcandidate toconnection.[[CurrentRemoteDescription]].sdp.

        4. Resolvep withundefined.

    8. Returnp.

A candidate isadministratively 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 UAMUST prohibit connections to addresses on the [Fetch]block bad port list, andMAY choose to prohibit connections to other addresses.

If theiceTransportPolicy member of theRTCConfiguration isrelay, 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

TherestartIce method tells theRTCPeerConnection that ICE should be restarted. Subsequent calls tocreateOffer will create descriptions that will restart ICE, as described in section 9.1.1.1 of [RFC5245].

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

  1. Letconnection be theRTCPeerConnection on which the method was invoked.

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

  3. Update the negotiation-needed flag forconnection.

getConfiguration

Returns anRTCConfiguration object representing the current configuration of thisRTCPeerConnection object.

When this method is called, the user agentMUST return theRTCConfiguration object stored in the[[Configuration]] internal slot.

setConfiguration

ThesetConfiguration method updates the configuration of thisRTCPeerConnection object. This includes changing the configuration of theICE 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 thesetConfiguration method is invoked, the user agentMUST run the following steps:

  1. Letconnection be theRTCPeerConnection on which the method was invoked.

  2. Ifconnection.[[IsClosed]] istrue,throw anInvalidStateError.

  3. Set the configuration specified byconfiguration.

close

When theclose method is invoked, the user agentMUST run the following steps:

  1. Letconnection be theRTCPeerConnection object on which the method was invoked.

  2. close the connection withconnection and the valuefalse.

Theclose the connection algorithm given aconnection and adisappear boolean, is as follows:

  1. Ifconnection.[[IsClosed]] istrue, abort these steps.

  2. Setconnection.[[IsClosed]] totrue.

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

  4. Lettransceivers be the result of executing theCollectTransceivers algorithm. For everyRTCRtpTransceivertransceiver intransceivers, run the following steps:

    1. Iftransceiver.[[Stopped]] istrue, abort these sub steps.

    2. Stop the RTCRtpTransceiver withtransceiver anddisappear.

  5. Set the[[ReadyState]] slot of each ofconnection'sRTCDataChannels to "closed".

    Note
    TheRTCDataChannels will be closed abruptly and the closing procedure will not be invoked.
  6. Ifconnection.[[SctpTransport]] is notnull, 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 ofconnection'sRTCDtlsTransports to "closed".

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

  9. Set the[[IceTransportState]] slot of each ofconnection'sRTCIceTransports to "closed".

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

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

4.4.3 Legacy Interface Extensions

Note
TheIDL definition of these methods are documented in the main definition of theRTCPeerConnection 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
TheaddStream method that used to exist onRTCPeerConnection 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 thecreateOffer method is called, the user agentMUST run the following steps:

  1. LetsuccessCallback be the method's first argument.

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

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

  4. Run the steps specified byRTCPeerConnection'screateOffer() method withoptions as the sole argument, and letp be the resulting promise.

  5. Uponfulfillment ofp with valueoffer, invokesuccessCallback withoffer as the argument.

  6. Uponrejection ofp with reasonr, invokefailureCallback withr as the argument.

  7. Return a promiseresolved withundefined.

setLocalDescription

When thesetLocalDescription method is called, the user agentMUST run the following steps:

  1. Letdescription be the method's first argument.

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

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

  4. Run the steps specified byRTCPeerConnection'ssetLocalDescription method withdescription as the sole argument, and letp be the resulting promise.

  5. Uponfulfillment ofp, invokesuccessCallback withundefined as the argument.

  6. Uponrejection ofp with reasonr, invokefailureCallback withr as the argument.

  7. Return a promiseresolved withundefined.

createAnswer
Note
The legacycreateAnswer method does not take anRTCAnswerOptions parameter, since no known legacycreateAnswer implementation ever supported it.

When thecreateAnswer method is called, the user agentMUST run the following steps:

  1. LetsuccessCallback be the method's first argument.

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

  3. Run the steps specified byRTCPeerConnection'screateAnswer() method with no arguments, and letp be the resulting promise.

  4. Uponfulfillment ofp with valueanswer, invokesuccessCallback withanswer as the argument.

  5. Uponrejection ofp with reasonr, invokefailureCallback withr as the argument.

  6. Return a promiseresolved withundefined.

setRemoteDescription

When thesetRemoteDescription method is called, the user agentMUST run the following steps:

  1. Letdescription be the method's first argument.

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

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

  4. Run the steps specified byRTCPeerConnection'ssetRemoteDescription method withdescription as the sole argument, and letp be the resulting promise.

  5. Uponfulfillment ofp, invokesuccessCallback withundefined as the argument.

  6. Uponrejection ofp with reasonr, invokefailureCallback withr as the argument.

  7. Return a promiseresolved withundefined.

addIceCandidate

When theaddIceCandidate method is called, the user agentMUST run the following steps:

  1. Letcandidate be the method's first argument.

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

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

  4. Run the steps specified byRTCPeerConnection'saddIceCandidate() method withcandidate as the sole argument, and letp be the resulting promise.

  5. Uponfulfillment ofp, invokesuccessCallback withundefined as the argument.

  6. Uponrejection ofp with reasonr, invokefailureCallback withr as the argument.

  7. Return a promiseresolved withundefined.

Callback Definitions

These callbacks are only used on the legacy APIs.

RTCPeerConnectionErrorCallback
WebIDLcallbackRTCPeerConnectionErrorCallback =undefined (DOMExceptionerror);
CallbackRTCPeerConnectionErrorCallback Parameters
error of typeDOMException
An error object encapsulating information about what went wrong.
RTCSessionDescriptionCallback
WebIDLcallbackRTCSessionDescriptionCallback =undefined (RTCSessionDescriptionInitdescription);
CallbackRTCSessionDescriptionCallback Parameters
description of typeRTCSessionDescriptionInit
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 theRTCPeerConnection. Developers are encouraged to use theRTCRtpTransceiver API instead.

WhencreateOffer is called with any of the legacy options specified in this section, run the followings steps instead of the regularcreateOffer steps:

  1. Letoptions be the methods first argument.

  2. Letconnection be the currentRTCPeerConnection object.

  3. For eachofferToReceive<Kind> member inoptions with kind,kind, run the following steps:

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

      2. For each non-stopped "recvonly" transceiver oftransceiver kindkind, settransceiver.[[Direction]] to "inactive".

      Continue with the next option, if any.

    2. Ifconnection has any non-stopped "sendrecv" or "recvonly" transceivers oftransceiver kindkind, continue with the next option, if any.

    3. Lettransceiver be the result of invoking the equivalent ofconnection.addTransceiver(kind), except that this operationMUST NOTupdate the negotiation-needed flag.

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

    5. Settransceiver.[[Direction]] to "recvonly".

  4. Run the steps specified bycreateOffer to create the offer.

WebIDLpartial dictionaryRTCOfferOptions {booleanofferToReceiveAudio;booleanofferToReceiveVideo;};
Attributes
offerToReceiveAudio of typeboolean

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 typeboolean

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

AnRTCPeerConnection objectMUST 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 istrue, no such event handler can be triggered and it is therefore safe to garbage collect the object.

AllRTCDataChannel andMediaStreamTrack objects that are connected to anRTCPeerConnection have a strong reference to theRTCPeerConnection 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.1RTCSdpType

TheRTCSdpType enum describes the type of anRTCSessionDescriptionInit,RTCLocalSessionDescriptionInit, orRTCSessionDescription instance.

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

AnRTCSdpType of "offer" indicates that a descriptionMUST be treated as an [SDP] offer.

pranswer

AnRTCSdpType of "pranswer" indicates that a descriptionMUST 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

AnRTCSdpType of "answer" indicates that a descriptionMUST be treated as an [SDP] final answer, and the offer-answer exchangeMUST 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

AnRTCSdpType of "rollback" indicates that a descriptionMUST 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 benull if there has not yet been a successful offer-answer negotiation. An "answer" or "pranswer" cannot be rolled back.

4.6.2RTCSessionDescription Class

TheRTCSessionDescription class is used byRTCPeerConnection to expose local and remote session descriptions.

WebIDL[Exposed=Window]interfaceRTCSessionDescription {constructor(RTCSessionDescriptionInitdescriptionInitDict);  readonly attributeRTCSdpTypetype;  readonly attributeDOMStringsdp;  [Default]RTCSessionDescriptionInittoJSON();};
Constructors
constructor()

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

Attributes
type of typeRTCSdpType, readonly
The type of this session description.
sdp of typeDOMString, readonly, defaulting to""
The string representation of the SDP [SDP].
Methods
toJSON()
When called, run [WEBIDL]'sdefault toJSON steps.
WebIDLdictionaryRTCSessionDescriptionInit {  requiredRTCSdpTypetype;DOMStringsdp = "";};
DictionaryRTCSessionDescriptionInit Members
type of typeRTCSdpType, required
The type of this session description.
sdp of typeDOMString
The string representation of the SDP [SDP]; iftype is "rollback", this member is unused.
WebIDLdictionaryRTCLocalSessionDescriptionInit {RTCSdpTypetype;DOMStringsdp = "";};
DictionaryRTCLocalSessionDescriptionInit Members
type of typeRTCSdpType
The type of this description. If not present, thensetLocalDescription will infer the type based on theRTCPeerConnection's[[SignalingState]].
sdp of typeDOMString
The string representation of the SDP [SDP]; iftype is "rollback", this member is unused.

4.7 Session Negotiation Model

Many changes to state of anRTCPeerConnection 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 thenegotiationneeded event. This event is fired according to the state of the connection'snegotiation-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 anRTCPeerConnection that requires signaling, the connection will be marked as needing negotiation. Examples of such operations include adding or stopping anRTCRtpTransceiver, or adding the firstRTCDataChannel.

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

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

4.7.2 Clearing Negotiation-Needed

This section is non-normative.

Thenegotiation-needed flag is cleared when a session description of type "answer"is set successfully, and the supplied description matches the state of theRTCRtpTransceivers andRTCDataChannels that currently exist on theRTCPeerConnection. Specifically, this means that all non-stopped transceivers have anassociated 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 forupdating 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 agentMUSTupdate the negotiation-needed flag.

Toupdate the negotiation-needed flag forconnection, run the following steps:

  1. If the length ofconnection.[[Operations]] is not0, then setconnection.[[UpdateNegotiationNeededFlagOnEmptyChain]] totrue, and abort these steps.

  2. Queue a task to run the following steps:

    1. Ifconnection.[[IsClosed]] istrue, abort these steps.

    2. If the length ofconnection.[[Operations]] is not0, then setconnection.[[UpdateNegotiationNeededFlagOnEmptyChain]] totrue, and abort these steps.

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

      Note

      Thenegotiation-needed flag will be updated once the state transitions to "stable", as part of the steps forsetting a session description.

    4. If the result ofchecking if negotiation is needed isfalse,clear the negotiation-needed flag by settingconnection.[[NegotiationNeeded]] tofalse, and abort these steps.

    5. Ifconnection.[[NegotiationNeeded]] is alreadytrue, abort these steps.

    6. Setconnection.[[NegotiationNeeded]] totrue.

    7. Fire an event namednegotiationneeded atconnection.

    Note

    The task queueing preventsnegotiationneeded from firing prematurely, in the common situation where multiple modifications toconnection are being made at once.

    Additionally, we avoid racing with negotiation methods by only firingnegotiationneeded when theoperations chain is empty.

Tocheck if negotiation is needed forconnection, perform the following checks:

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

  2. Ifconnection.[[LocalIceCredentialsToReplace]] is not empty, returntrue.

  3. Letdescription beconnection.[[CurrentLocalDescription]].

  4. Ifconnection has created anyRTCDataChannels, and no m= section indescription has been negotiated yet for data, returntrue.

  5. For eachtransceiver inconnection'sset of transceivers, perform the following checks:

    1. Iftransceiver.[[Stopping]] istrue andtransceiver.[[Stopped]] isfalse, returntrue.

    2. Iftransceiver isn'tstopped and isn't yetassociated with an m= section indescription, returntrue.

    3. Iftransceiver isn'tstopped and isassociated with an m= section indescription then perform the following checks:

      1. Iftransceiver.[[Direction]] is "sendrecv" or "sendonly", and theassociated m= section indescription either doesn't contain a singlea=msid line, or the number of MSIDs from thea=msid lines in thism= section, or the MSID values themselves, differ from what is intransceiver.sender.[[AssociatedMediaStreamIds]], returntrue.

      2. Ifdescription is of type "offer", and the direction of theassociated m= section in neitherconnection.[[CurrentLocalDescription]] norconnection.[[CurrentRemoteDescription]] matchestransceiver.[[Direction]], returntrue. 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. Ifdescription is of type "answer", and the direction of theassociated m= section in thedescription does not matchtransceiver.[[Direction]] intersected with the offered direction (as described in[RFC9429] (section 5.3.1.)), returntrue.

    4. Iftransceiver isstopped and isassociated with an m= section, but the associated m= section is not yet rejected inconnection.[[CurrentLocalDescription]] orconnection.[[CurrentRemoteDescription]], returntrue.

  6. If all the preceding checks were performed andtrue was not returned, nothing remains to be negotiated; returnfalse.

4.8 Interfaces for Interactive Connectivity Establishment

4.8.1RTCIceCandidate Interface

This interface describes an ICE candidate, described in [RFC5245] Section 2. Other thancandidate,sdpMid,sdpMLineIndex, andusernameFragment, the remaining attributes are derived from parsing thecandidate member incandidateInitDict, 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()

TheRTCIceCandidate() constructor takes a dictionary argument,candidateInitDict, whose content is used to initialize the newRTCIceCandidate object.

When invoked, run the following steps:

  1. If both thesdpMid andsdpMLineIndex members ofcandidateInitDict arenull,throw aTypeError.
  2. Return the result ofcreating an RTCIceCandidate withcandidateInitDict.

Tocreate an RTCIceCandidate with acandidateInitDict dictionary, run the following steps:

  1. LeticeCandidate be a newly createdRTCIceCandidate object.
  2. Create internal slots for the following attributes oficeCandidate, initilized tonull:foundation,component,priority,address,protocol,port,type,tcpType,relatedAddress, andrelatedPort.
  3. Create internal slots for the following attributes oficeCandidate, initilized to their namesakes incandidateInitDict:candidate,sdpMid,sdpMLineIndex,usernameFragment.
  4. Letcandidate be thecandidate dictionary member ofcandidateInitDict. Ifcandidate is not an empty string, run the following steps:
    1. Parsecandidate using thecandidate-attribute grammar.
    2. If parsing ofcandidate-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 iniceCandidate to the field values of the parsed result.
  5. ReturniceCandidate.
Note

The constructor forRTCIceCandidate only does basic parsing and type checking for the dictionary members incandidateInitDict. Detailed validation on the well-formedness ofcandidate,sdpMid,sdpMLineIndex,usernameFragment with the corresponding session description is done when passing theRTCIceCandidate object toaddIceCandidate().

To maintain backward compatibility, any error on parsing thecandidate attribute is ignored. In such case, thecandidate attribute holds the rawcandidate string given incandidateInitDict, but derivative attributes such asfoundation,priority, etc are set tonull.

Attributes

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

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

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

Remote candidates may be exposed, for instance via[[SelectedCandidatePair]].remote. By default, the user agentMUST leave theaddress attribute asnull for any exposed remote candidate. Once aRTCPeerConnection instance learns on an address by the web application usingaddIceCandidate, the user agent can expose theaddress attribute value in anyRTCIceCandidate of theRTCPeerConnection 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 inRTCIceCandidate 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 theICE Agent to report only relay candidates via theiceTransportPolicy member ofRTCConfiguration.

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 typeRTCIceProtocol, readonly, nullable
The protocol of the candidate ("udp"/"tcp"). This corresponds to thetransport field incandidate-attribute.
port of typeunsigned short, readonly, nullable
The port of the candidate.
type of typeRTCIceCandidateType, readonly, nullable
The type of the candidate. This corresponds to thecandidate-types field incandidate-attribute.
tcpType of typeRTCIceTcpCandidateType, readonly, nullable
Ifprotocol is "tcp",tcpType represents the type of TCP candidate. Otherwise,tcpType isnull. This corresponds to thetcp-type field incandidate-attribute.
relatedAddress of typeDOMString, readonly, nullable
For a candidate that is derived from another, such as a relay or reflexive candidate, therelatedAddress is the IP address of the candidate that it is derived from. For host candidates, therelatedAddress isnull. This corresponds to therel-address field incandidate-attribute.
relatedPort of typeunsigned short, readonly, nullable
For a candidate that is derived from another, such as a relay or reflexive candidate, therelatedPort is the port of the candidate that it is derived from. For host candidates, therelatedPort isnull. This corresponds to therel-port field incandidate-attribute.
usernameFragment of typeDOMString, readonly, nullable
This carries theufrag as defined in section 15.4 of [RFC5245].
Candidate Addition 16:Add RTCIceCandidate.relayProtocol (PR #2763)
relayProtocol of typeRTCIceServerTransportProtocol, 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 isnull.
Candidate Addition 23:Add RTCIceCandidate.url (PR #2773)
url of typeDOMString, 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 isnull.
Methods
toJSON()
To invoke thetoJSON() operation of theRTCIceCandidate interface, run the following steps:
  1. Letjson be a newRTCIceCandidateInit dictionary.
  2. For each attribute identifierattr in «candidate,sdpMid,sdpMLineIndex,usernameFragment»:
    1. Letvalue be the result of getting the underlying value of the attribute identified byattr, given thisRTCIceCandidate object.
    2. Setjson[attr] tovalue.
  3. Returnjson.
WebIDLdictionaryRTCIceCandidateInit {DOMStringcandidate = "";DOMString?sdpMid = null;unsigned short?sdpMLineIndex = null;DOMString?usernameFragment = null;};
DictionaryRTCIceCandidateInit Members
candidate of typeDOMString, defaulting to""
This carries thecandidate-attribute as defined in section 15.1 of [RFC5245]. If this represents an end-of-candidates indication,candidate is an empty string.
sdpMid of typeDOMString, nullable, defaulting tonull
If notnull, this contains themedia stream "identification-tag" defined in [RFC5888] for the media component this candidate is associated with.
sdpMLineIndex of typeunsigned short, nullable, defaulting tonull
If notnull, this indicates the index (starting at zero) of themedia description in the SDP this candidate is associated with.
usernameFragment of typeDOMString, nullable, defaulting tonull
If notnull, this carries theufrag as defined in section 15.4 of [RFC5245].
4.8.1.1candidate-attribute Grammar

Thecandidate-attribute grammar is used to parse thecandidate member ofcandidateInitDict in theRTCIceCandidate() constructor.

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

The browserMAY support other grammar extensions forcandidate-attribute as defined in other RFCs.

4.8.1.2RTCIceProtocol Enum

TheRTCIceProtocol represents the protocol of the ICE candidate.

WebIDLenumRTCIceProtocol {"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.3RTCIceTcpCandidateType Enum

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

WebIDLenumRTCIceTcpCandidateType {"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 gatheractive ICE TCP candidates.

4.8.1.4RTCIceCandidateType Enum

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

WebIDLenumRTCIceCandidateType {"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.5RTCIceServerTransportProtocol Enum

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

WebIDLenumRTCIceServerTransportProtocol {"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.2RTCPeerConnectionIceEvent

Theicecandidate event of theRTCPeerConnection uses theRTCPeerConnectionIceEvent interface.

When firing anRTCPeerConnectionIceEvent event that contains anRTCIceCandidate object, itMUST include values for bothsdpMid andsdpMLineIndex. If theRTCIceCandidate is of type "srflx" or type "relay", theurl property of the eventMUST be set to the URL of the ICE server from which the candidate was obtained.

Note
Theicecandidate event is used for three different types of indications:
WebIDL[Exposed=Window]interfaceRTCPeerConnectionIceEvent :Event {constructor(DOMStringtype, optionalRTCPeerConnectionIceEventIniteventInitDict = {});  readonly attributeRTCIceCandidate?candidate;  readonly attributeDOMString?url;};
Constructors
RTCPeerConnectionIceEvent.constructor()
Attributes
candidate of typeRTCIceCandidate, readonly, nullable

Thecandidate attribute is theRTCIceCandidate object with the new ICE candidate that caused the event.

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

Note

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

url of typeDOMString, readonly, nullable

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

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

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

WebIDLdictionaryRTCPeerConnectionIceEventInit :EventInit {RTCIceCandidate?candidate;DOMString?url;};
DictionaryRTCPeerConnectionIceEventInit Members
candidate of typeRTCIceCandidate, nullable

See thecandidate attribute of theRTCPeerConnectionIceEvent interface.

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

4.8.3RTCPeerConnectionIceErrorEvent

Theicecandidateerror event of theRTCPeerConnection uses theRTCPeerConnectionIceErrorEvent interface.

WebIDL[Exposed=Window]interfaceRTCPeerConnectionIceErrorEvent :Event {constructor(DOMStringtype,RTCPeerConnectionIceErrorEventIniteventInitDict);  readonly attributeDOMString?address;  readonly attributeunsigned short?port;  readonly attributeDOMStringurl;  readonly attributeunsigned shorterrorCode;  readonly attributeUSVStringerrorText;};
Constructors
RTCPeerConnectionIceErrorEvent.constructor()
Attributes
address of typeDOMString, readonly, nullable

Theaddress 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, theaddress attribute will be set tonull.

port of typeunsigned short, readonly, nullable

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

If theaddress attribute isnull, theport attribute is also set tonull.

url of typeDOMString, readonly

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

errorCode of typeunsigned short, readonly

TheerrorCode 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 theRTCIceGatheringState of "gathering".

errorText of typeUSVString, readonly

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

WebIDLdictionaryRTCPeerConnectionIceErrorEventInit :EventInit {DOMString?address;unsigned short?port;DOMStringurl;  requiredunsigned shorterrorCode;USVStringerrorText;};
DictionaryRTCPeerConnectionIceErrorEventInit Members
address of typeDOMString, nullable

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

port of typeunsigned short, nullable

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

url of typeDOMString

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

errorCode of typeunsigned short, required

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

errorText of typeUSVString

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

4.9 Certificate Management

The certificates thatRTCPeerConnection instances use to authenticate with peers use theRTCCertificate interface. These objects can be explicitly generated by applications using thegenerateCertificate method and can be provided in theRTCConfiguration when constructing a newRTCPeerConnection instance.

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

WebIDLpartial interfaceRTCPeerConnection {  staticPromise<RTCCertificate>generateCertificate(AlgorithmIdentifierkeygenAlgorithm);};

Methods

generateCertificate, static

ThegenerateCertificate function causes theuser agent to create an X.509 certificate [X509V3] and corresponding private key. A handle to information is provided in the form of theRTCCertificate interface. The returnedRTCCertificate can be used to control the certificate that is offered in the DTLS sessions established byRTCPeerConnection.

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

The following valuesMUST be supported by auser 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 auser 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 byRTCPeerConnection, 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 browserSHOULD select SHA-256 [FIPS-180-4] if a hash algorithm is needed.

The resulting certificateMUST NOT include information that can be linked to a user oruser agent. Randomized values for distinguished name and serial numberSHOULD be used.

When the method is called, the user agentMUST run the following steps:

  1. LetkeygenAlgorithm be the first argument togenerateCertificate.

  2. Letexpires 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 thegenerateCertificate call.

  3. IfkeygenAlgorithm is an object, run the following steps:

    1. LetcertificateExpiration be the result ofconverting the ECMAScript object represented bykeygenAlgorithm to anRTCCertificateExpiration dictionary.

    2. If the conversion fails with anerror, return a promise that isrejected witherror.

    3. IfcertificateExpiration.expires is notundefined, setexpires tocertificateExpiration.expires.

    4. Ifexpires is greater than 31536000000, setexpires to 31536000000.

      Note

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

      Auser agentMAY further cap the value ofexpires.

  4. LetnormalizedKeygenAlgorithm be the result ofnormalizing an algorithm with an operation name ofgenerateKey and asupportedAlgorithms value specific to production of certificates forRTCPeerConnection.

  5. If the above normalization step fails with anerror, return a promise that isrejected witherror.

  6. If thenormalizedKeygenAlgorithm parameter identifies an algorithm that theuser agent cannot or will not use to generate a certificate forRTCPeerConnection, return a promise that isrejected with aDOMException of typeNotSupportedError. In particular,normalizedKeygenAlgorithmMUST be an asymmetric algorithm that can be used to produce a signature used to authenticate DTLS connections.

  7. Letp be a new promise.

  8. Run the following stepsin parallel:

    1. Perform the generate key operation specified bynormalizedKeygenAlgorithm usingkeygenAlgorithm.

    2. LetgeneratedKeyingMaterial andgeneratedKeyCertificate be the private keying material and certificate generated by the above step.

    3. Letcertificate be a newRTCCertificate object.

    4. Setcertificate.[[Expires]] to the current time plusexpires value.

    5. Setcertificate.[[Origin]] to therelevant settings object'sorigin.

    6. Store thegeneratedKeyingMaterial in a secure module, and lethandle be a reference identifier to it.

    7. Setcertificate.[[KeyingMaterialHandle]] tohandle.

    8. Setcertificate.[[Certificate]] togeneratedCertificate.

    9. Queue a global task on thenetworking task source given the current realm'sglobal object asglobal toresolvep withcertificate.

  9. Returnp.

4.9.1RTCCertificateExpiration Dictionary

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

WebIDLdictionaryRTCCertificateExpiration {  [EnforceRange]unsigned long longexpires;};
expires, of type unsigned long long

An optionalexpires attributeMAY be added to the definition of the algorithm that is passed togenerateCertificate. If this parameter is present it indicates the maximum time in milliseconds that theRTCCertificate is valid for, measured from the time the certificate is created.

4.9.2RTCCertificate Interface

TheRTCCertificate 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]]) thatRTCPeerConnection uses to authenticate with a peer, and the origin ([[Origin]]) that created the object.

WebIDL[Exposed=Window,Serializable]interfaceRTCCertificate {  readonly attributeEpochTimeStampexpires;sequence<RTCDtlsFingerprint>getFingerprints();};
Attributes
expires of typeEpochTimeStamp, readonly

Theexpires 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 anRTCPeerConnection using this certificate fail.

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

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. ImplementationsMUST support applications storing and retrievingRTCCertificate objects from persistent storage, in a manner that also preserves the keying material referenced by[[KeyingMaterialHandle]]. ImplementationsSHOULD 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 areserializable objects [HTML]. Theirserialization steps, givenvalue andserialized, are:

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

Theirdeserialization steps, givenserialized andvalue, are:

  1. Initializevalue.expires attribute to containserialized.[[Expires]].
  2. Setvalue.[[Certificate]] to a copy of serialized.[[Certificate]]
  3. Setvalue.[[Origin]] to a copy ofserialized.[[Origin]]
  4. Setvalue.[[KeyingMaterialHandle]] to the private keying material handle resulting from deserializingserialized.[[KeyingMaterialHandle]]
Note

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

5. RTP Media API

TheRTP media API lets a web application send and receiveMediaStreamTracks over a peer-to-peer connection. Tracks, when added to anRTCPeerConnection, 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 oneRTCPeerConnection 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 anRTCRtpSender without creating a new track on the receiver side; the correspondingRTCRtpReceiver will only have a single track, potentially representing multiple sources of media stitched together. BothaddTransceiver andreplaceTrack 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 anRTCRtpSender on one side and anRTCRtpReceiver's track on the other side, matching senders and receivers using theRTCRtpTransceiver'smid 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 videoMAY be downscaled. The mediaMUST NOT be upscaled to create fake data that did not occur in the input source, the mediaMUST NOT be cropped except as needed to satisfy constraints on pixel counts, and the aspect ratioMUST 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 inGitHub issue 1283.

Whenever video is rescaled as a result ofscaleResolutionDownBy, situations when the resulting width or height is not an integer may occur. The user agentMUST NOT transmit video larger thanthe integer part of the scaled width and height fromscaleResolutionDownBy, except to respect an encoder's minimum resolution. What to transmit if the integer part of the scaled width or height is zero isimplementation-defined.

The actual encoding and transmission ofMediaStreamTracks is managed through objects calledRTCRtpSenders. Similarly, the reception and decoding ofMediaStreamTracks is managed through objects calledRTCRtpReceivers. EachRTCRtpSender is associated with at most one track, and each track to be received is associated with exactly oneRTCRtpReceiver.

The encoding and transmission of eachMediaStreamTrackSHOULD be made such that its characteristics (width,height andframeRate for video tracks;sampleSize,sampleRate andchannelCount 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 beRTCRtpSender settings applied that instruct the implementation to act differently.

AnRTCPeerConnection object contains aset ofRTCRtpTransceivers, representing the paired senders and receivers with some shared state.This set is initialized to the empty set when theRTCPeerConnection object is created.RTCRtpSenders andRTCRtpReceivers are always created at the same time as anRTCRtpTransceiver, which they will remain attached to for their lifetime.RTCRtpTransceivers are created implicitly when the application attaches aMediaStreamTrack to anRTCPeerConnection via theaddTrack() method, or explicitly when the application uses theaddTransceiver 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 relevantMediaStreamTrack andRTCRtpReceiver are surfaced to the application via thetrack event.

In order for anRTCRtpTransceiver to send and/or receive media with another endpoint this must be negotiated with SDP such that both endpoints have anRTCRtpTransceiver object that isassociated with the samemedia 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 theaddTrack() method may be associated. Disassociated transceivers created via theaddTransceiver() 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 enoughaddTrack()-created transceivers. This setsaddTrack()-created andaddTransceiver()-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 usingaddTrack()-created transceivers, making sure that enough media descriptions are offered in the initial exchange.

5.1 RTCPeerConnection Interface Extensions

The RTP media API extends theRTCPeerConnection interface as described below.

WebIDL          partial interfaceRTCPeerConnection {sequence<RTCRtpSender>getSenders();sequence<RTCRtpReceiver>getReceivers();sequence<RTCRtpTransceiver>getTransceivers();RTCRtpSenderaddTrack(MediaStreamTracktrack,MediaStream...streams);undefinedremoveTrack(RTCRtpSendersender);RTCRtpTransceiveraddTransceiver((MediaStreamTrack orDOMString)trackOrKind,                                   optionalRTCRtpTransceiverInitinit = {});  attributeEventHandlerontrack;};

Attributes

ontrack of typeEventHandler

The event type of this event handler istrack.

Methods

getSenders

Returns a sequence ofRTCRtpSender objects representing the RTP senders that belong to non-stoppedRTCRtpTransceiver objects currently attached to thisRTCPeerConnection object.

When thegetSenders method is invoked, the user agentMUST return the result of executing theCollectSenders algorithm.

We define theCollectSenders algorithm as follows:

  1. Lettransceivers be the result of executing theCollectTransceivers algorithm.
  2. Letsenders be a new empty sequence.
  3. For eachtransceiver intransceivers,
    1. Iftransceiver.[[Stopped]] isfalse, addtransceiver.[[Sender]] tosenders.
  4. Returnsenders.
getReceivers

Returns a sequence ofRTCRtpReceiver objects representing the RTP receivers that belong to non-stoppedRTCRtpTransceiver objects currently attached to thisRTCPeerConnection object.

When thegetReceivers method is invoked, the user agentMUST run the following steps:

  1. Lettransceivers be the result of executing theCollectTransceivers algorithm.
  2. Letreceivers be a new empty sequence.
  3. For each transceiver intransceivers,
    1. Iftransceiver.[[Stopped]] isfalse, addtransceiver.[[Receiver]] toreceivers.
  4. Returnreceivers.
getTransceivers

Returns a sequence ofRTCRtpTransceiver objects representing the RTP transceivers that are currently attached to thisRTCPeerConnection object.

ThegetTransceivers methodMUST return the result of executing theCollectTransceivers algorithm.

We define theCollectTransceivers algorithm as follows:

  1. Lettransceivers be a new sequence consisting of allRTCRtpTransceiver objects in thisRTCPeerConnection object'sset of transceivers, in insertion order.
  2. Returntransceivers.
addTrack

Adds a new track to theRTCPeerConnection, and indicates that it is contained in the specifiedMediaStreams.

When theaddTrack method is invoked, the user agentMUST run the following steps:

  1. Letconnection be theRTCPeerConnection object on which this method was invoked.

  2. Lettrack be theMediaStreamTrack object indicated by the method's first argument.

  3. Letkind betrack.kind.

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

  5. Ifconnection.[[IsClosed]] istrue,throw anInvalidStateError.

  6. Letsenders be the result of executing theCollectSenders algorithm. If anRTCRtpSender fortrack already exists insenders,throw anInvalidAccessError.

  7. The steps below describe how to determine if an existing sender can be reused. Doing so will cause future calls tocreateOffer andcreateAnswer to mark the correspondingmedia description assendrecv orsendonly and add the MSID of the sender's streams, as defined in[RFC9429] (section 5.2.2. andsection 5.3.2.).

    If anyRTCRtpSender object insenders matches all the following criteria, letsender be that object, ornull otherwise:

  8. Ifsender is notnull, run the following steps to use that sender:

    1. Setsender.[[SenderTrack]] totrack.

    2. Setsender.[[AssociatedMediaStreamIds]] to an empty set.

    3. For eachstream instreams, addstream.id to[[AssociatedMediaStreamIds]] if it's not already there.

    4. Lettransceiver be theRTCRtpTransceiver associated withsender.

    5. Iftransceiver.[[Direction]] is "recvonly", settransceiver.[[Direction]] to "sendrecv".

    6. Iftransceiver.[[Direction]] is "inactive", settransceiver.[[Direction]] to "sendonly".

  9. Ifsender isnull, run the following steps:

    1. Create an RTCRtpSender withtrack,kind andstreams, and letsender be the result.

    2. Create an RTCRtpReceiver withkind, and letreceiver be the result.

    3. Create an RTCRtpTransceiver withsender,receiver and anRTCRtpTransceiverDirection value of "sendrecv", and lettransceiver be the result.

    4. Addtransceiver toconnection'sset of transceivers.

  10. A track could have contents that are inaccessible to the application. This can be due to anything that would make a trackCORS cross-origin. These tracks can be supplied to theaddTrack() method, and have anRTCRtpSender created for them, but contentMUST 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 forconnection.

  12. Returnsender.

removeTrack

Stops sending media fromsender. TheRTCRtpSender will still appear ingetSenders. Doing so will cause future calls tocreateOffer to mark themedia 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 remoteMediaStreams that were initially revealed in thetrack event, and if theMediaStreamTrack is not already muted, amute event is fired at the track.

Note
The same effect asremoveTrack() can be achieved by setting theRTCRtpTransceiver.direction attribute of the corresponding transceiver and invokingRTCRtpSender.replaceTrack(null) on the sender. One minor difference is thatreplaceTrack() is asynchronous andremoveTrack() is synchronous.

When theremoveTrack method is invoked, the user agentMUST run the following steps:

  1. Letsender be the argument toremoveTrack.

  2. Letconnection be theRTCPeerConnection object on which the method was invoked.

  3. Ifconnection.[[IsClosed]] istrue,throw anInvalidStateError.

  4. Ifsender was not created byconnection,throw anInvalidAccessError.

  5. Lettransceiver be theRTCRtpTransceiver object corresponding tosender.

  6. Iftransceiver.[[Stopping]] istrue, abort these steps.

  7. Letsenders be the result of executing theCollectSenders algorithm.

  8. Ifsender is not insenders (which indicates its transceiver was stopped or removed due tosetting a session description oftype "rollback"), then abort these steps.

  9. Ifsender.[[SenderTrack]] is null, abort these steps.

  10. Setsender.[[SenderTrack]] to null.

  11. Iftransceiver.[[Direction]] is "sendrecv", settransceiver.[[Direction]] to "recvonly".

  12. Iftransceiver.[[Direction]] is "sendonly", settransceiver.[[Direction]] to "inactive".

  13. Update the negotiation-needed flag forconnection.

addTransceiver

Create a newRTCRtpTransceiver and add it to theset of transceivers.

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

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

ThesendEncodings 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 agentMUST run the following steps:

  1. Letinit be the second argument.

  2. Letstreams beinit.streams.

  3. LetsendEncodings beinit.sendEncodings.

  4. Letdirection beinit.direction.

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

    1. Ifkind is neither"audio" nor"video",throw aTypeError.

    2. Lettrack benull.

  6. If the first argument is aMediaStreamTrack, lettrack be the first argument and letkind betrack.kind.

  7. Ifconnection.[[IsClosed]] istrue,throw anInvalidStateError.

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

    1. Candidate Correction 18:TypeError unless all or none of encodings have rids and on duplicate rids (PR #2774,PR #2775)
    2. Verify that eachrid value insendEncodings conforms to the grammar specified in Section 10 of [RFC8851]. If one of the RIDs does not meet these requirements,throw aTypeError.

      If any of the following conditions are met,throw aTypeError:
      • Any encodingcontains arid member whose value does not conform to the grammar requirements specified in Section 10 of [RFC8851].
      • Some but not all encodingscontain arid member.
      • Any encodingcontains arid member whose value is the same as that of aridcontained in another encoding insendEncodings.
    3. If any encodingcontains aread-only parameter other thanrid,throw anInvalidAccessError.

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

      If any encodingcontains acodec member whose value doesnot match any codec inRTCRtpSender.getCapabilities(kind).codecs,throw anOperationError.

    5. 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 promiserejected with a newlycreatedOperationError.

    6. Ifkind is"audio", remove thescaleResolutionDownBy andmaxFramerate members from all encodings thatcontain any of them.

    7. If any encodingcontains ascaleResolutionDownBy member whose value is less than1.0,throw aRangeError.

    8. Verify that the value of eachmaxFramerate member insendEncodings that is defined is greater than 0.0. If one of themaxFramerate values does not meet this requirement,throw aRangeError.

    9. LetmaxN be the maximum number of total simultaneous encodings the user agent may support for thiskind, at minimum1.This should be an optimistic number since the codec to be used is not known yet.

    10. If any encodingcontains ascaleResolutionDownBy member, then for each encoding without one, add ascaleResolutionDownBy member with the value1.0.

    11. If the number of encodings stored insendEncodings exceedsmaxN, then trimsendEncodings from the tail until its length ismaxN.

    12. Ifkind is"video" and none of the encodingscontain ascaleResolutionDownBy member, then for each encoding, add ascaleResolutionDownBy member with the value2^(length ofsendEncodings - 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.

    13. If the number of encodings now stored insendEncodings is1, then remove anyrid member from the lone entry.

      Note
      Providing a single, defaultRTCRtpEncodingParameters insendEncodings allows the application to subsequently set encoding parameters usingsetParameters, even when simulcast isn't used.
  9. Create an RTCRtpSender withtrack,kind,streams andsendEncodings and letsender be the result.

    IfsendEncodings is set, then subsequent calls tocreateOffer will be configured to send multiple RTP encodings as defined in[RFC9429] (section 5.2.2. andsection 5.2.1.). WhensetRemoteDescription is called with a corresponding remote description that is able to receive multiple RTP encodings as defined in[RFC9429] (section 3.7.), theRTCRtpSender may send multiple RTP encodings and the parameters retrieved via the transceiver'ssender.getParameters() will reflect the encodings negotiated.

  10. Create an RTCRtpReceiver withkind and letreceiver be the result.

  11. Create an RTCRtpTransceiver withsender,receiver anddirection, and lettransceiver be the result.

  12. Addtransceiver toconnection'sset of transceivers.

  13. Update the negotiation-needed flag forconnection.

  14. Returntransceiver.

WebIDLdictionaryRTCRtpTransceiverInit {RTCRtpTransceiverDirectiondirection = "sendrecv";sequence<MediaStream>streams = [];sequence<RTCRtpEncodingParameters>sendEncodings = [];};

DictionaryRTCRtpTransceiverInit Members

direction of typeRTCRtpTransceiverDirection, defaulting to "sendrecv"
The direction of theRTCRtpTransceiver.
streams of typesequence<MediaStream>

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

sendEncodings of typesequence<RTCRtpEncodingParameters>

A sequence containing parameters for sending RTP encodings of media.

WebIDLenumRTCRtpTransceiverDirection {"sendrecv","sendonly","recvonly","inactive","stopped"};
RTCRtpTransceiverDirection Enumeration description
Enum valueDescription
sendrecv TheRTCRtpTransceiver'sRTCRtpSendersender will offer to send RTP, and will send RTP if the remote peer accepts andsender.getParameters().encodings[i].active istrue for any value ofi. TheRTCRtpTransceiver'sRTCRtpReceiver will offer to receive RTP, and will receive RTP if the remote peer accepts.
sendonly TheRTCRtpTransceiver'sRTCRtpSendersender will offer to send RTP, and will send RTP if the remote peer accepts andsender.getParameters().encodings[i].active istrue for any value ofi. TheRTCRtpTransceiver'sRTCRtpReceiver will not offer to receive RTP, and will not receive RTP.
recvonly TheRTCRtpTransceiver'sRTCRtpSender will not offer to send RTP, and will not send RTP. TheRTCRtpTransceiver'sRTCRtpReceiver will offer to receive RTP, and will receive RTP if the remote peer accepts.
inactive TheRTCRtpTransceiver'sRTCRtpSender will not offer to send RTP, and will not send RTP. TheRTCRtpTransceiver'sRTCRtpReceiver will not offer to receive RTP, and will not receive RTP.
stopped TheRTCRtpTransceiver will neither send nor receive RTP. It will generate a zero port in the offer. In answers, itsRTCRtpSender will not offer to send RTP, and itsRTCRtpReceiver 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 callRTCRtpTransceiver.stop() and subsequently initiate negotiation from its end.

Toprocess remote tracks given anRTCRtpTransceivertransceiver,direction,msids,addList,removeList, andtrackEventInits, run the following steps:

  1. Set the associated remote streams withtransceiver.[[Receiver]],msids,addList, andremoveList.

  2. Ifdirection is "sendrecv" or "recvonly" andtransceiver.[[FiredDirection]] is neither "sendrecv" nor "recvonly", or the previous step increased the length ofaddList,process the addition of a remote track withtransceiver andtrackEventInits.

  3. Ifdirection is "sendonly" or "inactive", settransceiver.[[Receptive]] tofalse.

  4. Ifdirection is "sendonly" or "inactive", andtransceiver.[[FiredDirection]] is either "sendrecv" or "recvonly",process the removal of a remote track for themedia description, withtransceiver andmuteTracks.

  5. Settransceiver.[[FiredDirection]] todirection.

Toprocess the addition of a remote track given anRTCRtpTransceivertransceiver andtrackEventInits, run the following steps:

  1. Letreceiver betransceiver.[[Receiver]].

  2. Lettrack bereceiver.[[ReceiverTrack]].

  3. Letstreams bereceiver.[[AssociatedRemoteMediaStreams]].

  4. Create a newRTCTrackEventInit dictionary withreceiver,track,streams andtransceiver as members and add it totrackEventInits.

Toprocess the removal of a remote track with anRTCRtpTransceivertransceiver andmuteTracks, run the following steps:

  1. Letreceiver betransceiver.[[Receiver]].

  2. Lettrack bereceiver.[[ReceiverTrack]].

  3. Iftrack.muted isfalse, addtrack tomuteTracks.

Toset the associated remote streams givenRTCRtpReceiverreceiver,msids,addList, andremoveList, run the following steps:

  1. Letconnection be theRTCPeerConnection object associated withreceiver.

  2. For each MSID inmsids, unless aMediaStream object has previously been created with thatid for thisconnection, create aMediaStream object with thatid.

  3. Letstreams be a list of theMediaStream objects created for thisconnection with theids corresponding tomsids.

  4. Lettrack bereceiver.[[ReceiverTrack]].

  5. For eachstream inreceiver.[[AssociatedRemoteMediaStreams]] that is not present instreams, addstream andtrack as a pair toremoveList.

  6. For eachstream instreams that is not present inreceiver.[[AssociatedRemoteMediaStreams]], addstream andtrack as a pair toaddList.

  7. Setreceiver.[[AssociatedRemoteMediaStreams]] tostreams.

5.2RTCRtpSender Interface

TheRTCRtpSender interface allows an application to control how a givenMediaStreamTrack is encoded and transmitted to a remote peer. WhensetParameters is called on anRTCRtpSender object, the encoding is changed appropriately.

Tocreate an RTCRtpSender with aMediaStreamTrack,track, a string,kind, a list ofMediaStream objects,streams, and optionally a list ofRTCRtpEncodingParameters objects,sendEncodings, run the following steps:

  1. Letsender be a newRTCRtpSender object.

  2. Letsender have a[[SenderTrack]] internal slot initialized totrack.

  3. Letsender have a[[SenderTransport]] internal slot initialized tonull.

  4. Letsender have a[[LastStableStateSenderTransport]] internal slot initialized tonull.

  5. Letsender have a[[Dtmf]] internal slot initialized tonull.

  6. Ifkind is"audio" thencreate an RTCDTMFSenderdtmf and set the[[Dtmf]] internal slot todtmf.

  7. Letsender have an[[AssociatedMediaStreamIds]] internal slot, representing a list of Ids ofMediaStream objects that this sender is to be associated with. The[[AssociatedMediaStreamIds]] slot is used whensender is represented in SDP as described in[RFC9429] (section 5.2.1.).

  8. Setsender.[[AssociatedMediaStreamIds]] to an empty set.

  9. For eachstream instreams, addstream.id to[[AssociatedMediaStreamIds]] if it's not already there.

  10. Letsender have a[[SendEncodings]] internal slot, representing a list ofRTCRtpEncodingParameters dictionaries.

  11. IfsendEncodings is given as input to this algorithm, and is non-empty, set the[[SendEncodings]] slot tosendEncodings. Otherwise, set it to a list containing a single newRTCRtpEncodingParameters dictionary, and ifkind is"video", add ascaleResolutionDownBy member with the value1.0 to that dictionary.

    Note

    RTCRtpEncodingParameters dictionaries containactive members whose values aretrue by default.

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

    Letsender have a[[LastStableRidlessSendEncodings]] internal slot initialized tonull.

  13. Letsender have a[[SendCodecs]] internal slot, representing a list ofRTCRtpCodecParameters dictionaries, and initialized to an empty list.

  14. Letsender have a[[LastReturnedParameters]] internal slot, which will be used to matchgetParameters andsetParameters transactions.

  15. Returnsender.

WebIDL[Exposed=Window]interfaceRTCRtpSender {  readonly attributeMediaStreamTrack?track;  readonly attributeRTCDtlsTransport?transport;  staticRTCRtpCapabilities?getCapabilities(DOMStringkind);Promise<undefined>setParameters(RTCRtpSendParametersparameters,      optionalRTCSetParameterOptionssetParameterOptions = {});RTCRtpSendParametersgetParameters();Promise<undefined>replaceTrack(MediaStreamTrack?withTrack);undefinedsetStreams(MediaStream...streams);Promise<RTCStatsReport>getStats();};

Attributes

track of typeMediaStreamTrack, readonly, nullable

Thetrack attribute is the track that is associated with thisRTCRtpSender object. Iftrack is ended, or if the track's output is disabled, i.e. the track is disabled and/or muted, theRTCRtpSenderMUST send black frames (video) andMUST NOT send (audio). In the case of video, theRTCRtpSenderSHOULD send one black frame per second. Iftrack isnull then theRTCRtpSender does not send. On getting, the attributeMUST return the value of the[[SenderTrack]] slot.

transport of typeRTCDtlsTransport, readonly, nullable

Thetransport attribute is the transport over which media fromtrack is sent in the form of RTP packets. Prior to construction of theRTCDtlsTransport object, thetransport attribute will be null. When bundling is used, multipleRTCRtpSender objects will share onetransport and will all send RTP and RTCP over the same transport.

On getting, the attributeMUST return the value of the[[SenderTransport]] slot.

Methods

getCapabilities, static

The staticRTCRtpSender.getCapabilities() method provides a way to discover the types of capabilities the user agent supports for sending media of the given kind, without reserving any resources, ports, or other state.

When thegetCapabilities method is called, the user agentMUST run the following steps:

  1. Letkind be the method's first argument.

  2. Ifkind is neither"video" nor"audio" returnnull.

  3. Return a newRTCRtpCapabilities dictionary, with itscodecs member initialized to thelist of implemented send codecs forkind, and itsheaderExtensions member initialized to thelist of implemented header extensions for sending withkind.

Thelist of implemented send codecs, givenkind, is animplementation-defined list ofRTCRtpCodec dictionaries representing the most optimistic view of the codecs the user agent supports for sending media of the givenkind (video or audio).

Thelist of implemented header extensions for sending, givenkind, is animplementation-defined list ofRTCRtpHeaderExtensionCapability dictionaries representing the most optimistic view of the header extensions the user agent supports for sending media of the givenkind (video or audio).

These capabilities provide generally persistent cross-origin information on the device and thus increases the fingerprinting surface of the application. In privacy-sensitive contexts, user agentsMAY consider mitigations such as reporting only a common subset of the capabilities.(This is a fingerprinting vector.)

Note

The codec capabilities returned affect thesetCodecPreferences() algorithm and what inputs it throwsInvalidModificationError on, and should also be consistent with information revealed bycreateOffer() andcreateAnswer() about codecs negotiated for sending, to ensure any privacy mitigations are effective.

setParameters

ThesetParameters method updates howtrack is encoded and transmitted to a remote peer.

When thesetParameters method is called, the user agentMUST run the following steps:

  1. Letparameters be the method's first argument.
  2. Letsender be theRTCRtpSender object on whichsetParameters is invoked.
  3. Lettransceiver be theRTCRtpTransceiver object associated withsender (i.e.sender istransceiver.[[Sender]]).
  4. Iftransceiver.[[Stopping]] istrue, return a promiserejected with a newlycreatedInvalidStateError.
  5. If sender.[[LastReturnedParameters]] isnull, return a promiserejected with a newlycreatedInvalidStateError.
  6. Validateparameters by running the following setParameters validation steps:
    1. Letencodings beparameters.encodings.
    2. Letcodecs be parameters.codecs.
    3. Candidate Addition 49:Add codec to RTCRtpEncodingParameters (PR #2985)

      LetchoosableCodecs becodecs.

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

      IfchoosableCodecs is an empty list, setchoosableCodecs to transceiver.[[PreferredCodecs]] and exclude any codecs not included in thelist of implemented send codecs.

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

      IfchoosableCodecs is still an empty list, setchoosableCodecs to thelist of implemented send codecs for transceiver's kind.

    6. LetN be the number ofRTCRtpEncodingParameters stored insender.[[SendEncodings]].
    7. If any of the following conditions are met, return a promiserejected with a newlycreatedInvalidModificationError:
      • encodings.length is different fromN.
      • encodings has been re-ordered.
      • Any parameter inparameters is marked as aRead-only parameter (such as RID) and has a value that is different from the corresponding parameter value insender.[[LastReturnedParameters]]. Note that this also applies totransactionId.
      • Candidate Addition 49:Add codec to RTCRtpEncodingParameters (PR #2985)
        Anyencoding in encodingscontains a codec not found inchoosableCodecs, using thecodec dictionary match algorithm withignoreLevels set totrue.
    8. Iftransceiver kind is"audio", remove thescaleResolutionDownBy andmaxFramerate members from allencodings thatcontain any of them.

    9. Iftransceiver kind is"video", then for each encoding inencodings that doesn'tcontain ascaleResolutionDownBy member, add ascaleResolutionDownBy member with the value1.0.

    10. Iftransceiver kind is"video", and any encoding inencodingscontains ascaleResolutionDownBy member whose value is less than1.0, return a promiserejected with a newlycreatedRangeError.

    11. Verify that each encoding inencodings has amaxFramerate member whose value is greater than or equal to 0.0. If one of themaxFramerate values does not meet this requirement, return a promiserejected with a newlycreatedRangeError.

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

      If the user agent does not support setting the codec for any encoding or mixing different codec values on the different encodings, return a promiserejected with a newlycreatedOperationError.

  7. Letp be a new promise.
  8. In parallel, configure the media stack to useparameters to transmitsender.[[SenderTrack]].
    1. If the media stack is successfully configured withparameters, queue a task to run the following steps:
      1. Setsender.[[LastReturnedParameters]] tonull.
      2. Setsender.[[SendEncodings]] toparameters.encodings.
      3. Resolvep withundefined.
    2. If any error occurred while configuring the media stack, queue a task to run the following steps:
      1. If an error occurred due to hardware resources not being available,rejectp with a newly createdRTCError whoseerrorDetail is set to "hardware-encoder-not-available" and abort these steps.
      2. If an error occurred due to a hardware encoder not supportingparameters,rejectp with a newly createdRTCError whoseerrorDetail is set to "hardware-encoder-error" and abort these steps.
      3. For all other errors,rejectp with a newlycreatedOperationError.
  9. Returnp.

setParameters does not cause SDP renegotiation and can only be used to change what the media stack is sending or receiving within the envelope negotiated by Offer/Answer. The attributes in theRTCRtpSendParameters dictionary are designed to not enable this, so attributes likecname that cannot be changed are read-only. Other things, like bitrate, are controlled using limits such asmaxBitrate, where the user agent needs to ensure it does not exceed the maximum bitrate specified bymaxBitrate, while at the same time making sure it satisfies constraints on bitrate specified in other places such as the SDP.

getParameters

ThegetParameters() method returns theRTCRtpSender object's current parameters for howtrack is encoded and transmitted to a remoteRTCRtpReceiver.

WhengetParameters is called, the user agentMUST run the following steps:

  1. Letsender be theRTCRtpSender object on which the getter was invoked.

  2. Ifsender.[[LastReturnedParameters]] is notnull, returnsender.[[LastReturnedParameters]], and abort these steps.

  3. Letresult be a newRTCRtpSendParameters dictionary constructed as follows:

  4. Setsender.[[LastReturnedParameters]] toresult.

  5. Queue a task that setssender.[[LastReturnedParameters]] tonull.

  6. Returnresult.

getParameters may be used withsetParameters to change the parameters in the following way:

asyncfunctionupdateParameters() {try {const params = sender.getParameters();// ... make changes to parameters    params.encodings[0].active =false;await sender.setParameters(params);  }catch (err) {console.error(err);  }}

After a completed call tosetParameters, subsequent calls togetParameters will return the modified set of parameters.

replaceTrack

Attempts to replace theRTCRtpSender's currenttrack with another track provided (or with anull track), without renegotiation.

When thereplaceTrack method is invoked, the user agentMUST run the following steps:

  1. Letsender be theRTCRtpSender object on whichreplaceTrack is invoked.

  2. Lettransceiver be theRTCRtpTransceiver object associated withsender.

  3. Letconnection be theRTCPeerConnection object associated withsender.

  4. LetwithTrack be the argument to this method.

  5. IfwithTrack is non-null andwithTrack.kind differs from thetransceiver kind oftransceiver, return a promiserejected with a newlycreatedTypeError.

  6. Return the result ofchaining the following steps toconnection'soperations chain:

    1. Iftransceiver.[[Stopping]] istrue, return a promiserejected with a newlycreatedInvalidStateError.

    2. Letp be a new promise.

    3. Letsending betrue iftransceiver.[[CurrentDirection]] is "sendrecv" or "sendonly", andfalse otherwise.

    4. Run the following stepsin parallel:

      1. Ifsending istrue, andwithTrack isnull, have the sender stop sending.

      2. Ifsending istrue, andwithTrack is notnull, determine ifwithTrack can be sent immediately by the sender without violating the sender's already-negotiated envelope, and if it cannot, then:

        1. Queue a global task on thenetworking task source given the current realm'sglobal object asglobal torejectp with a newlycreatedInvalidModificationError.
        2. Abort these steps.
      3. Ifsending istrue, andwithTrack is notnull, have the sender switch seamlessly to transmittingwithTrack instead of the sender's existing track.

      4. Queue a task that runs the following steps:

        1. Ifconnection.[[IsClosed]] istrue, abort these steps.

        2. Setsender.[[SenderTrack]] towithTrack.

        3. Queue a global task on thenetworking task source given the current realm'sglobal object asglobal toresolvep withundefined.

    5. Returnp.

Note

Changing dimensions and/or frame rates might not require negotiation. Cases that may require negotiation include:

  1. Changing a resolution to a value outside of the negotiated imageattr bounds, as described in [RFC6236].
  2. Changing a frame rate to a value that causes the block rate for the codec to be exceeded.
  3. A video track differing in raw vs. pre-encoded format.
  4. An audio track having a different number of channels.
  5. Sources that also encode (typically hardware encoders) might be unable to produce the negotiated codec; similarly, software sources might not implement the codec that was negotiated for an encoding source.
setStreams

Sets theMediaStreams to be associated with this sender's track.

When thesetStreams method is invoked, the user agentMUST run the following steps:

  1. Letsender be theRTCRtpSender object on which this method was invoked.

  2. Letconnection be theRTCPeerConnection object on which this method was invoked.

  3. Ifconnection.[[IsClosed]] istrue,throw anInvalidStateError.

  4. Letstreams be a list ofMediaStream objects constructed from the method's arguments, or an empty list if the method was called without arguments.

  5. Setsender.[[AssociatedMediaStreamIds]] to an empty set.

  6. For eachstream instreams, addstream.id to[[AssociatedMediaStreamIds]] if it's not already there.

  7. Update the negotiation-needed flag forconnection.

getStats

Gathers stats for this sender only and reports the result asynchronously.

When thegetStats() method is invoked, the user agentMUST run the following steps:

  1. Letselector be theRTCRtpSender object on which the method was invoked.

  2. Letp be a new promise, and run the following stepsin parallel:

    1. Gather the stats indicated byselector according to thestats selection algorithm.

    2. Queue a global task on thenetworking task source given the current realm'sglobal object asglobal toresolvep with the resultingRTCStatsReport object, containing the gathered stats.

  3. Returnp.

5.2.1RTCRtpParameters Dictionary

WebIDLdictionaryRTCRtpParameters {  requiredsequence<RTCRtpHeaderExtensionParameters>headerExtensions;  requiredRTCRtcpParametersrtcp;  requiredsequence<RTCRtpCodecParameters>codecs;};
DictionaryRTCRtpParameters Members
headerExtensions of typesequence<RTCRtpHeaderExtensionParameters>, required

A sequence containing parameters for RTP header extensions.Read-only parameter.

rtcp of typeRTCRtcpParameters, required

Parameters used for RTCP.Read-only parameter.

codecs of typesequence<RTCRtpCodecParameters>, required

A sequence containing the media codecs that anRTCRtpSender will choose from, as well as entries for RTX, RED and FEC mechanisms. Corresponding to each media codec where retransmission via RTX is enabled, there will be an entry incodecs with amimeType attribute indicating retransmission viaaudio/rtx orvideo/rtx, and ansdpFmtpLine attribute (providing the "apt" and "rtx-time" parameters).Read-only parameter.

5.2.2RTCRtpSendParameters Dictionary

WebIDLdictionaryRTCRtpSendParameters :RTCRtpParameters {  requiredDOMStringtransactionId;  requiredsequence<RTCRtpEncodingParameters>encodings;};
DictionaryRTCRtpSendParameters Members
transactionId of typeDOMString, required

A unique identifier for the last set of parameters applied. Ensures thatsetParameters can only be called based on a previousgetParameters, and that there are no intervening changes.Read-only parameter.

encodings of typesequence<RTCRtpEncodingParameters>, required

A sequence containing parameters for RTP encodings of media.

5.2.3RTCRtpReceiveParameters Dictionary

WebIDLdictionaryRTCRtpReceiveParameters :RTCRtpParameters {};

5.2.4RTCRtpCodingParameters Dictionary

WebIDLdictionaryRTCRtpCodingParameters {DOMStringrid;};
DictionaryRTCRtpCodingParameters Members
rid of typeDOMString

If set, this RTP encoding will be sent with the RID header extension as defined by[RFC9429] (section 5.2.1.). The RID is not modifiable viasetParameters. It can only be set or modified inaddTransceiver on the sending side.Read-only parameter.

5.2.5RTCRtpEncodingParameters Dictionary

WebIDLdictionaryRTCRtpEncodingParameters :RTCRtpCodingParameters {booleanactive = true;RTCRtpCodeccodec;unsigned longmaxBitrate;doublemaxFramerate;doublescaleResolutionDownBy;};
DictionaryRTCRtpEncodingParameters Members
active of typeboolean, defaulting totrue

Indicates that this encoding is actively being sent. Setting it tofalse causes this encoding to no longer be sent. Setting it totrue causes this encoding to be sent. Since setting the value tofalse does not cause the SSRC to be removed, an RTCP BYE is not sent.

Candidate Addition 49:Add codec to RTCRtpEncodingParameters (PR #2985)
codec of typeRTCRtpCodec

Optional value selecting which codec is used for this encoding's RTP stream. If absent, the user agent can choose to use any codec negotiated for sending.

Whencodec is set and[[SendCodecs]] have been negotiated, the user agentSHOULD use the first[[SendCodecs]] matchingcodec for sending, according to thecodec dictionary match algorithm withignoreLevels set totrue.

maxBitrate of typeunsigned long

When present, indicates the maximum bitrate that can be used to send this encoding. The user agent is free to allocate bandwidth between the encodings, as long as themaxBitrate value is not exceeded. The encoding may also be further constrained by other limits (such as per-transport or per-session bandwidth limits) below the maximum specified here.maxBitrate is computed the same way as the Transport Independent Application Specific Maximum (TIAS) bandwidth defined in [RFC3890] Section 6.2.2, which is the maximum bandwidth needed without counting IP or other transport layers like TCP or UDP. The unit ofmaxBitrate is bits per second.

Note

How the bitrate is achieved is media and encoding dependent. For video, a frame will always be sent as fast as possible, but frames may be dropped until bitrate is low enough. Thus, even a bitrate of zero will allow sending one frame. For audio, it might be necessary to stop playing if the bitrate does not allow the chosen encoding enough bandwidth to be sent.

maxFramerate of typedouble

This member can only be present if the sender'skind is"video". When present, indicates the maximum frame rate that can be used to send this encoding, in frames per second. Theuser agent is free to allocate bandwidth between the encodings, as long as themaxFramerate value is not exceeded.

If changed withsetParameters(), the new frame rate takes effect after the current picture is completed; setting the max frame rate to zero thus has the effect of freezing the video on the next frame.

scaleResolutionDownBy of typedouble

This member is only present if the sender'skind is"video". The video's resolution will be scaled down in each dimension by the given value before sending. For example, if the value is 2.0, the video will be scaled down by a factor of 2 in each dimension, resulting in sending a video of one quarter the size. If the value is 1.0, the video will not be affected. The value must be greater than or equal to 1.0. By default, scaling is applied in reverse order by a factor of two, to produce an order of smaller to higher resolutions, e.g. 4:2:1. If there is only one layer, the sender will by default not apply any scaling, (i.e.scaleResolutionDownBy will be 1.0).

5.2.6RTCRtcpParameters Dictionary

WebIDLdictionaryRTCRtcpParameters {DOMStringcname;booleanreducedSize;};
DictionaryRTCRtcpParameters Members
cname of typeDOMString

The Canonical Name (CNAME) used by RTCP (e.g. in SDES messages).Read-only parameter.

reducedSize of typeboolean

Whether reduced size RTCP [RFC5506] is configured (if true) or compound RTCP as specified in [RFC3550] (if false).Read-only parameter.

5.2.7RTCRtpHeaderExtensionParameters Dictionary

WebIDLdictionaryRTCRtpHeaderExtensionParameters {  requiredDOMStringuri;  requiredunsigned shortid;booleanencrypted = false;};
uri of typeDOMString, required

The URI of the RTP header extension, as defined in [RFC5285].Read-only parameter.

id of typeunsigned short, required

The value put in the RTP packet to identify the header extension.Read-only parameter.

encrypted of typeboolean

Whether the header extension is encrypted or not.Read-only parameter.

Note

TheRTCRtpHeaderExtensionParameters dictionary enables an application to determine whether a header extension is configured for use within anRTCRtpSender orRTCRtpReceiver. For anRTCRtpTransceivertransceiver, an application can determine the "direction" parameter (defined in Section 5 of [RFC5285]) of a header extension as follows without having to parse SDP:

  1. sendonly: The header extension is only included intransceiver.sender.getParameters().headerExtensions.
  2. recvonly: The header extension is only included intransceiver.receiver.getParameters().headerExtensions.
  3. sendrecv: The header extension is included in bothtransceiver.sender.getParameters().headerExtensions andtransceiver.receiver.getParameters().headerExtensions.
  4. inactive: The header extension is included in neithertransceiver.sender.getParameters().headerExtensions nortransceiver.receiver.getParameters().headerExtensions.

5.2.8RTCRtpCodec Dictionary

WebIDLdictionaryRTCRtpCodec {  requiredDOMStringmimeType;  requiredunsigned longclockRate;unsigned shortchannels;DOMStringsdpFmtpLine;};
DictionaryRTCRtpCodec Members

TheRTCRtpCodec dictionary provides information about codec objects.

mimeType of typeDOMString, required

The codec MIME media type/subtype. Valid media types and subtypes are listed in [IANA-RTP-2].

clockRate of typeunsigned long, required

The codec clock rate expressed in Hertz.

channels of typeunsigned short

If present, indicates the maximum number of channels (mono=1, stereo=2).

sdpFmtpLine of typeDOMString

The "format specific parameters" field from thea=fmtp line in the SDP corresponding to the codec, if one exists, as defined by[RFC9429] (section 5.8.).

5.2.9RTCRtpCodecParameters Dictionary

WebIDLdictionaryRTCRtpCodecParameters :RTCRtpCodec {  requiredoctetpayloadType;};
DictionaryRTCRtpCodecParameters Members

TheRTCRtpCodecParameters dictionary provides information about the negotiated codecs. The fields inherited fromRTCRtpCodecMUST all beRead-only parameters.

For anRTCRtpSender, thesdpFmtpLine parameters come from the[[CurrentRemoteDescription]], and for anRTCRtpReceiver, they come from the local description (which is[[PendingLocalDescription]] if notnull, and[[CurrentLocalDescription]] otherwise).

payloadType of typeoctet, required

The RTP payload type used to identify this codec.Read-only parameter.

5.2.10RTCRtpCapabilities Dictionary

WebIDLdictionaryRTCRtpCapabilities {  requiredsequence<RTCRtpCodec>codecs;  requiredsequence<RTCRtpHeaderExtensionCapability>headerExtensions;};
DictionaryRTCRtpCapabilities Members
codecs of typesequence<RTCRtpCodec>, required

Supported media codecs as well as entries for RTX, RED and FEC mechanisms. Only combinations that would utilize distinct payload types in a generated SDP offer are to be provided. For example:

  1. Two H.264/AVC codecs, one for each of two supported packetization-mode values.
  2. Two CN codecs with different clock rates.

ThereMUST only be a single entry incodecs for retransmission via RTX, withsdpFmtpLine not present.

headerExtensions of typesequence<RTCRtpHeaderExtensionCapability>, required

Supported RTP header extensions.

5.2.11RTCRtpHeaderExtensionCapability Dictionary

WebIDLdictionaryRTCRtpHeaderExtensionCapability {  requiredDOMStringuri;};
uri of typeDOMString, required

The URI of the RTP header extension, as defined in [RFC5285].

5.2.12RTCSetParameterOptions Dictionary

WebIDLdictionaryRTCSetParameterOptions {};
DictionaryRTCSetParameterOptions Members

RTCSetParameterOptions is defined as an empty dictionary to allow for extensibility.

5.3RTCRtpReceiver Interface

TheRTCRtpReceiver interface allows an application to inspect the receipt of aMediaStreamTrack.

Tocreate an RTCRtpReceiver with a string,kind, run the following steps:

  1. Letreceiver be a newRTCRtpReceiver object.

  2. Lettrack be a newMediaStreamTrack object [GETUSERMEDIA]. The source oftrack is aremote source provided byreceiver. Note that thetrack.id is generated by theuser agent and does not map to any track IDs on the remote side.

  3. Initializetrack.kind tokind.

  4. Initializetrack.label to the result of concatenating the string"remote " withkind.

  5. Initializetrack.readyState tolive.

  6. Initializetrack.muted totrue. See theMediaStreamTrack section about how themuted attribute reflects if aMediaStreamTrack is receiving media data or not.

  7. Letreceiver have a[[ReceiverTrack]] internal slot initialized totrack.

  8. Letreceiver have a[[ReceiverTransport]] internal slot initialized tonull.

  9. Letreceiver have a[[LastStableStateReceiverTransport]] internal slot initialized tonull.

  10. Letreceiver have an[[AssociatedRemoteMediaStreams]] internal slot, representing a list ofMediaStream objects that theMediaStreamTrack object of this receiver is associated with, and initialized to an empty list.

  11. Letreceiver have a[[LastStableStateAssociatedRemoteMediaStreams]] internal slot and initialize it to an empty list.

  12. Letreceiver have a[[ReceiveCodecs]] internal slot, representing a list ofRTCRtpCodecParameters dictionaries, and initialized to an empty list.

  13. Letreceiver have a[[LastStableStateReceiveCodecs]] internal slot and initialize it to an empty list.

  14. Letreceiver have a[[JitterBufferTarget]] internal slot initialized tonull.

  15. Returnreceiver.

WebIDL[Exposed=Window]interfaceRTCRtpReceiver {  readonly attributeMediaStreamTracktrack;  readonly attributeRTCDtlsTransport?transport;  staticRTCRtpCapabilities?getCapabilities(DOMStringkind);RTCRtpReceiveParametersgetParameters();sequence<RTCRtpContributingSource>getContributingSources();sequence<RTCRtpSynchronizationSource>getSynchronizationSources();Promise<RTCStatsReport>getStats();  attributeDOMHighResTimeStamp?jitterBufferTarget;};

Attributes

track of typeMediaStreamTrack, readonly

Thetrack attribute is the track that is associated with thisRTCRtpReceiver objectreceiver.

Note thattrack.stop() is final, although clones are not affected. Sincereceiver.track.stop() does not implicitly stopreceiver, Receiver Reports continue to be sent. On getting, the attributeMUST return the value of the[[ReceiverTrack]] slot.

transport of typeRTCDtlsTransport, readonly, nullable

Thetransport attribute is the transport over which media for the receiver'strack is received in the form of RTP packets. Prior to construction of theRTCDtlsTransport object, thetransport attribute will benull. When bundling is used, multipleRTCRtpReceiver objects will share onetransport and will all receive RTP and RTCP over the same transport.

On getting, the attributeMUST return the value of the[[ReceiverTransport]] slot.

jitterBufferTarget of typeDOMHighResTimeStamp, nullable

This attribute allows the application to specify a target duration of time in milliseconds of media for theRTCRtpReceiver's jitter buffer to hold. This influences the amount of buffering done by theuser agent, which in turn affects retransmissions and packet loss recovery. Altering the target value allows applications to control the tradeoff between playout delay and the risk of running out of audio or video frames due to network jitter.

Theuser agentMUST have aminimum allowed target and amaximum allowed target reflecting what theuser agent is able or willing to provide based on network conditions and memory constraints, which can change at any time.

Note

This is a target value. The resulting change in delay can be gradually observed over time. The receiver's average jitter buffer delay can be measured as the deltajitterBufferDelay divided by the deltajitterBufferEmittedCount.

An average delay is expected even if DTX is used. For example, if DTX is used and packets start flowing after silence, larger targets can influence theuser agent to buffer these packets rather than playing them out.

On getting, this attributeMUST return the value of the[[JitterBufferTarget]] internal slot.

On setting, theuser agentMUST run the following steps:

  1. Letreceiver be theRTCRtpReceiver object on which the setter is invoked.

  2. Lettarget be the argument to the setter.

  3. Iftarget is negative or larger than 4000 milliseconds, thenthrow aRangeError.

  4. Setreceiver's[[JitterBufferTarget]] totarget.

  5. Lettrack bereceiver's[[ReceiverTrack]].

  6. in parallel, begin executing the following steps:

    1. Update the underlying system about the newtarget, or that there is no application preference iftarget isnull.

      Iftrack is synchronized with anotherRTCRtpReceiver's track foraudio/video synchronization, then theuser agentSHOULD use the larger of the two receivers'[[JitterBufferTarget]] for both receivers.

      When the underlying system is applying a jitter buffer target, it will continuously make sure that the actual jitter buffer target is clamped within theminimum allowed target andmaximum allowed target.

      Note

      If theuser agent ends up using a target different from the requested one (e.g. due to network conditions or physical memory constraints), this is not reflected in the[[JitterBufferTarget]] internal slot.

    2. Modifying the jitter buffer target of the underlying systemSHOULD affect the internal audio or video buffering gradually in order not to hurt user experience. Audio samples or video framesSHOULD be accelerated or decelerated before playout, similarly to how it is done for audio/video synchronization or in response to congestion control.

      The acceleration or deceleration rate may vary depending on network conditions or the type of audio received (e.g. speech or background noise). ItMAY take several seconds to achieve 1 second of buffering butSHOULD not take more than 30 seconds assuming packets are being received. The speedMAY be different for audio and video.

      Note

      For audio, acceleration and deceleration can be measured withinsertedSamplesForDeceleration andremovedSamplesForAcceleration. For video, this may result in the same frame being rendered multiple times or frames may be dropped.

Methods

getCapabilities, static

The staticRTCRtpReceiver.getCapabilities() method provides a way to discover the types of capabilities the user agent supports for receiving media of the given kind, without reserving any resources, ports, or other state.

When thegetCapabilities method is called, the user agentMUST run the following steps:

  1. Letkind be the method's first argument.

  2. Ifkind is neither"video" nor"audio" returnnull.

  3. Return a newRTCRtpCapabilities dictionary, with itscodecs member initialized to thelist of implemented receive codecs forkind, and itsheaderExtensions member initialized to thelist of implemented header extensions for receiving forkind.

Thelist of implemented receive codecs, givenkind, is animplementation-defined list ofRTCRtpCodec dictionaries representing the most optimistic view of the codecs the user agent supports for receiving media of the givenkind (video or audio).

Thelist of implemented header extensions for receiving, givenkind, is animplementation-defined list ofRTCRtpHeaderExtensionCapability dictionaries representing an optimistic view of the header extensions the user agent supports for receiving media of the givenkind (video or audio).

These capabilities provide generally persistent cross-origin information on the device and thus increases the fingerprinting surface of the application. In privacy-sensitive contexts, user agentsMAY consider mitigations such as reporting only a common subset of the capabilities.(This is a fingerprinting vector.)

Note

The codec capabilities returned affect thesetCodecPreferences() algorithm and what inputs it throwsInvalidModificationError on, and should also be consistent with information revealed bycreateOffer() andcreateAnswer() about codecs negotiated for reception, to ensure any privacy mitigations are effective.

getParameters

ThegetParameters() method returns theRTCRtpReceiver object's current parameters for howtrack is decoded.

WhengetParameters is called, theRTCRtpReceiveParameters dictionary is constructed as follows:

  • TheheaderExtensions sequence is populated based on the header extensions that the receiver is currently prepared to receive.
  • codecs is set to the value of the[[ReceiveCodecs]] internal slot.

    Note
    Both the local and remote description may affect this list of codecs. For example, if three codecs are offered, the receiver will be prepared to receive each of them and will return them all fromgetParameters. But if the remote endpoint only answers with two, the absent codec will no longer be returned bygetParameters as the receiver no longer needs to be prepared to receive it.
  • rtcp.reducedSize is set totrue if the receiver is currently prepared to receive reduced-size RTCP packets, andfalse otherwise.rtcp.cname is left out.
getContributingSources

Returns anRTCRtpContributingSource for each unique CSRC identifier received by thisRTCRtpReceiver in the last 10 seconds, in descendingtimestamp order.

getSynchronizationSources

Returns anRTCRtpSynchronizationSource for each unique SSRC identifier received by thisRTCRtpReceiver in the last 10 seconds, in descendingtimestamp order.

getStats

Gathers stats for this receiver only and reports the result asynchronously.

When thegetStats() method is invoked, the user agentMUST run the following steps:

  1. Letselector be theRTCRtpReceiver object on which the method was invoked.

  2. Letp be a new promise, and run the following stepsin parallel:

    1. Gather the stats indicated byselector according to thestats selection algorithm.

    2. Queue a global task on thenetworking task source given the current realm'sglobal object asglobal toresolvep with the resultingRTCStatsReport object, containing the gathered stats.

  3. Returnp.

TheRTCRtpContributingSource andRTCRtpSynchronizationSource dictionaries contain information about a given contributing source (CSRC) or synchronization source (SSRC) respectively. When an audio or video frame from one or more RTP packets is delivered to theRTCRtpReceiver'sMediaStreamTrack, the user agentMUST queue a task to update the relevant information for theRTCRtpContributingSource andRTCRtpSynchronizationSource dictionaries based on the content of those packets. The information relevant to theRTCRtpSynchronizationSource dictionary corresponding to the SSRC identifier, is updated each time, and if an RTP packet contains CSRC identifiers, then the information relevant to theRTCRtpContributingSource dictionaries corresponding to those CSRC identifiers is also updated. The user agentMUST process RTP packets in order of ascending RTP timestamps. The user agentMUST keep information from RTP packets delivered to theRTCRtpReceiver'sMediaStreamTrack in the previous 10 seconds.

Note
Even if theMediaStreamTrack is not attached to any sink for playout,getSynchronizationSources andgetContributingSources returns up-to-date information as long as the track is not ended; sinks are not a prerequisite for decoding RTP packets.
Note
As stated in theconformance section, requirements phrased as algorithms may be implemented in any manner so long as the end result is equivalent. So, an implementation does not need to literally queue a task for every frame, as long as the end result is that within a single event loop task execution, all returnedRTCRtpSynchronizationSource andRTCRtpContributingSource dictionaries for a particularRTCRtpReceiver contain information from a single point in the RTP stream.
WebIDLdictionaryRTCRtpContributingSource {  requiredDOMHighResTimeStamptimestamp;  requiredunsigned longsource;doubleaudioLevel;  requiredunsigned longrtpTimestamp;};

Dictionary RTCRtpContributingSource Members

timestamp of typeDOMHighResTimeStamp, required

Thetimestamp indicating the most recent time a frame from an RTP packet, originating from this source, was delivered to theRTCRtpReceiver'sMediaStreamTrack. Thetimestamp is defined asPerformance.timeOrigin +Performance.now() at that time.

source of typeunsigned long, required

The CSRC or SSRC identifier of the contributing or synchronization source.

audioLevel of typedouble

Only present for audio receivers. This is a value between 0..1 (linear), where 1.0 represents 0 dBov, 0 represents silence, and 0.5 represents approximately 6 dBSPL change in the sound pressure level from 0 dBov.

For CSRCs, thisMUST be converted from the level value defined in [RFC6465] if the RFC 6465 header extension is present, otherwise this memberMUST be absent.

For SSRCs, thisMUST be converted from the level value defined in [RFC6464]. If the RFC 6464 header extension is not present in the received packets (such as if the other endpoint is not a user agent or is a legacy endpoint), this valueSHOULD be absent.

Both RFCs define the level as an integral value from 0 to 127 representing the audio level in negative decibels relative to the loudest signal that the system could possibly encode. Thus, 0 represents the loudest signal the system could possibly encode, and 127 represents silence.

To convert these values to the linear 0..1 range, a value of 127 is converted to 0, and all other values are converted using the equation:10^(-rfc_level/20).

rtpTimestamp of typeunsigned long, required

The RTP timestamp, as defined in [RFC3550] Section 5.1, of the media played out attimestamp.

WebIDLdictionaryRTCRtpSynchronizationSource :RTCRtpContributingSource {};

TheRTCRtpSynchronizationSource dictionary is expected to serve as an extension point for the specification to surface data only available in SSRCs.

5.4RTCRtpTransceiver Interface

TheRTCRtpTransceiver interface represents a combination of anRTCRtpSender and anRTCRtpReceiver that share a commonmedia stream "identification-tag". As defined in[RFC9429] (section 3.4.1.), anRTCRtpTransceiver is said to beassociated with amedia description if its "mid" property is non-null and matches amedia stream "identification-tag" in themedia description; otherwise it is said to be disassociated with thatmedia description.

Note

ARTCRtpTransceiver may become associated with a new pending description in RFC9429 while still being disassociated with the current description. This may happen incheck if negotiation is needed.

Thetransceiver kind of anRTCRtpTransceiver is defined by the kind of the associatedRTCRtpReceiver'sMediaStreamTrack object.

Tocreate an RTCRtpTransceiver with anRTCRtpReceiver object,receiver,RTCRtpSender object,sender, and anRTCRtpTransceiverDirection value,direction, run the following steps:

  1. Lettransceiver be a newRTCRtpTransceiver object.

  2. Lettransceiver have a[[Sender]] internal slot, initialized tosender.

  3. Lettransceiver have a[[Receiver]] internal slot, initialized toreceiver.

  4. Lettransceiver have a[[Stopping]] internal slot, initialized tofalse.

  5. Lettransceiver have a[[Stopped]] internal slot, initialized tofalse.

  6. Lettransceiver have a[[Direction]] internal slot, initialized todirection.

  7. Lettransceiver have a[[Receptive]] internal slot, initialized tofalse.

  8. Lettransceiver have a[[CurrentDirection]] internal slot, initialized tonull.

  9. Lettransceiver have a[[FiredDirection]] internal slot, initialized tonull.

  10. Lettransceiver have a[[PreferredCodecs]] internal slot, initialized to an empty list.

  11. Lettransceiver have a[[JsepMid]] internal slot, initialized tonull. This is the "RtpTransceiver mid property" defined in[RFC9429] (section 5.2.1. andsection 5.3.1.), and is only modified there.

  12. Lettransceiver have a[[Mid]] internal slot, initialized tonull.

  13. Returntransceiver.

Note
Creating a transceiver does not create the underlyingRTCDtlsTransport andRTCIceTransport objects. This will only occur as part of the process ofsetting a session description.
WebIDL[Exposed=Window]interfaceRTCRtpTransceiver {  readonly attributeDOMString?mid;  [SameObject] readonly attributeRTCRtpSendersender;  [SameObject] readonly attributeRTCRtpReceiverreceiver;  attributeRTCRtpTransceiverDirectiondirection;  readonly attributeRTCRtpTransceiverDirection?currentDirection;undefinedstop();undefinedsetCodecPreferences(sequence<RTCRtpCodec>codecs);};

Attributes

mid of typeDOMString, readonly, nullable

Themid attribute is themedia stream "identification-tag" negotiated and present in the local and remote descriptions. On getting, the attributeMUST return the value of the[[Mid]] slot.

sender of typeRTCRtpSender, readonly

Thesender attribute exposes theRTCRtpSender corresponding to the RTP media that may be sent with mid =[[Mid]]. On getting, the attributeMUST return the value of the[[Sender]] slot.

receiver of typeRTCRtpReceiver, readonly

Thereceiver attribute is theRTCRtpReceiver corresponding to the RTP media that may be received with mid =[[Mid]]. On getting the attributeMUST return the value of the[[Receiver]] slot.

direction of typeRTCRtpTransceiverDirection

As defined in[RFC9429] (section 4.2.4.), thedirection attribute indicates the preferred direction of this transceiver, which will be used in calls tocreateOffer andcreateAnswer. An update of directionality does not take effect immediately. Instead, future calls tocreateOffer andcreateAnswer mark the correspondingmedia description assendrecv,sendonly,recvonly orinactive as defined in[RFC9429] (section 5.2.2. andsection 5.3.2.)

On getting, the user agentMUST run the following steps:

  1. Lettransceiver be theRTCRtpTransceiver object on which the getter is invoked.

  2. Iftransceiver.[[Stopping]] istrue, return "stopped".

  3. Otherwise, return the value of the[[Direction]] slot.

On setting, the user agentMUST run the following steps:

  1. Lettransceiver be theRTCRtpTransceiver object on which the setter is invoked.

  2. Letconnection be theRTCPeerConnection object associated withtransceiver.

  3. Iftransceiver.[[Stopping]] istrue,throw anInvalidStateError.

  4. LetnewDirection be the argument to the setter.

  5. IfnewDirection is equal totransceiver.[[Direction]], abort these steps.

  6. IfnewDirection is equal to "stopped",throw aTypeError.

  7. Settransceiver.[[Direction]] tonewDirection.

  8. Update the negotiation-needed flag forconnection.

currentDirection of typeRTCRtpTransceiverDirection, readonly, nullable

As defined in[RFC9429] (section 4.2.5.), thecurrentDirection attribute indicates the current direction negotiated for this transceiver. The value ofcurrentDirection is independent of the value ofRTCRtpEncodingParameters.active since one cannot be deduced from the other. If this transceiver has never been represented in an offer/answer exchange, the value isnull. If the transceiver isstopped, the value is "stopped".

On getting, the user agentMUST run the following steps:

  1. Lettransceiver be theRTCRtpTransceiver object on which the getter is invoked.

  2. Iftransceiver.[[Stopped]] istrue, return "stopped".

  3. Otherwise, return the value of the[[CurrentDirection]] slot.

Methods

stop

Irreversibly marks the transceiver asstopping, unless it is alreadystopped. This will immediately cause the transceiver's sender to no longer send, and its receiver to no longer receive. Callingstop() alsoupdates the negotiation-needed flag for theRTCRtpTransceiver's associatedRTCPeerConnection.

Astopping transceiver will cause future calls tocreateOffer to generate a zero port in themedia description for the corresponding transceiver, as defined in[RFC9429] (section 4.2.1.) (The user agentMUST treat astopping transceiver asstopped for the purposes of RFC9429 only in this case). However, to avoid problems with [RFC8843], a transceiver that isstopping, but notstopped, will not affectcreateAnswer.

Astopped transceiver will cause future calls tocreateOffer orcreateAnswer to generate a zero port in themedia description for the corresponding transceiver, as defined in[RFC9429] (section 4.2.1.).

The transceiver will remain in thestopping state, unless it becomesstopped bysetRemoteDescription processing a rejected m-line in a remote offer or answer.

Note

A transceiver that isstopping but notstopped will always need negotiation. In practice, this means that callingstop() on a transceiver will cause the transceiver to becomestopped eventually, provided negotiation is allowed to complete on both ends.

When thestop method is invoked, the user agentMUST run the following steps:

  1. Lettransceiver be theRTCRtpTransceiver object on which the method is invoked.

  2. Letconnection be theRTCPeerConnection object associated withtransceiver.

  3. Ifconnection.[[IsClosed]] istrue,throw anInvalidStateError.

  4. Iftransceiver.[[Stopping]] istrue, abort these steps.

  5. Stop sending and receiving withtransceiver.

  6. Update the negotiation-needed flag forconnection.

Thestop sending and receiving algorithm given atransceiver and, optionally, adisappear boolean defaulting tofalse, is as follows:

  1. Letsender betransceiver.[[Sender]].

  2. Letreceiver betransceiver.[[Receiver]].

  3. In parallel, stop sending media withsender, and send an RTCP BYE for each RTP stream that was being sent bysender, as specified in [RFC3550].

  4. In parallel, stop receiving media withreceiver.

  5. Ifdisappear isfalse, execute the steps forreceiver.[[ReceiverTrack]] to beended. This fires an event.

  6. Settransceiver.[[Direction]] to "inactive".

  7. Settransceiver.[[Stopping]] totrue.

Thestop the RTCRtpTransceiver algorithm given atransceiver and, optionally, adisappear boolean defaulting tofalse, is as follows:

  1. Iftransceiver.[[Stopping]] isfalse,stop sending and receiving withtransceiver anddisappear.

  2. Settransceiver.[[Stopped]] totrue.

  3. Settransceiver.[[Receptive]] tofalse.

  4. Settransceiver.[[CurrentDirection]] tonull.

setCodecPreferences
Candidate Addition 51:setCodecPreferences supports both send and receive codecs (filtered by direction) (PR #3018)

ThesetCodecPreferences method overrides the default codec preferences used by theuser agent as input to negotiation.WhenWhengenerating a session descriptionusing eitherusing eithercreateOffer orcreateAnswer, theuser agentMUSTuseMUST filtertheindicated codecspreferred codecs ondirection and,if this resultsinthe ordera non-empty list, itMUST use thespecifiedcodecsinthethe order of thecodecsargument, for the mediasectionsectioncorresponding tothisthisRTCRtpTransceiver.

This method allows applications to disable the negotiation of specific codecs (including RTX/RED/FEC).It also allows an application to cause a remote peer to prefer the codec that appears first in the listby listing all codecs exceptforsendingthe ones to disable.

Note

If the m= section is used for receiving, the order of the codecs in the SDP (both the offer and the answer) tells the remote endpoint which codec the local endpoint prefers to receive. Even if the m= section is not used for receiving, an answerer that does not have any codec preferences of their own defaults to using the same order for its SDP answer.

Note

AnRTCRtpSender defaults to sending what the remote endpoint indicated that it prefers to receive, but the application can change which codec to send amongst negotiatedcodecs by callingsetParameters and specifying whichcodec to send. AnRTCRtpReceiver is prepared to receive any negotiated codec.

Codec preferences remain in effect for all calls tocreateOffer andcreateAnswer that include thisRTCRtpTransceiver until this method is called again. Settingcodecs to an emptysequence resets codec preferences to anysequence, or one that becomes empty afterdirection filtering, results indefaultvaluecodec preferences.

Note

Codecs have their payload types listed under each m= section in the SDP, defining the mapping between payload types and codecs. These payload types are referenced by the m=video or m=audio lines in the order of preference, and codecs that are not negotiated do not appear in this list as defined in section 5.2.1 of [RFC8829RFC9429]. A previously negotiated codec that is subsequently removed disappears from the m=video or m=audio line, and while its codec payload type is not to be reused in future offers or answers, its payload type may also be removed from the mapping of payload types in the SDP.

Thecodecs sequence passed intosetCodecPreferencescan only containwill reject attempts to setcodecsnot matchingcodecsthat are returned byfound in eitherRTCRtpSender.getCapabilities(kind) orRTCRtpReceiver.getCapabilities(kind), wherekind is the kind of theRTCRtpTransceiver on which the method is called. Additionally, theRTCRtpCodecCapability dictionary members cannot be modified. Ifcodecs does not fulfill these requirements, the user agentMUSTthrow anInvalidModificationError.

Note

Due to a recommendation in [SDP], calls tocreateAnswerSHOULD use only the common subset of the codec preferences and the codecs that appear in the offer. For example, if codec preferences are "C, B, A", but only codecs "A, B" were offered, the answer should only contain codecs "B, A". However,[RFC8829] (section 5.3.1.) allows adding codecs that were not in the offer, so implementations can behave differently.

WhensetCodecPreferences()inisinvoked, theuser agentMUST run the following steps:

  1. Lettransceiver be theRTCRtpTransceiver object this method was invoked on.

  2. Letcodecs be the first argument.

  3. Ifcodecs is an empty list, settransceiver.[[PreferredCodecs]] tocodecs and abort these steps.

  4. Remove any duplicate values incodecs. Start at the back of the list such that the priority of the codecs is maintained; the index of the first occurrence of a codec within the list is the same before and after this step.

  5. Remove anyduplicate values incodecs, ensuring that the first occurrence of each value remains in place.

  6. Letkind be thetransceiver'stransceiver kind.

  7. If the intersection betweencodecs andRTCRtpSender.getCapabilities(kind).codecs or the intersection betweencodecs andRTCRtpReceiver.getCapabilities(kind).codecs only contains RTX, RED or FEC codecs or is an empty set, throwInvalidModificationError. This ensures that we always have something to offer, regardless oftransceiver.direction.

  8. LetcodecCapabilities be the union ofRTCRtpSender.getCapabilities(kind).codecs andRTCRtpReceiver.getCapabilities(kind).codecs.

  9. For eachcodec incodecs,

    1. Ifcodec is not incodecCapabilities, throwInvalidModificationError.
  10. For eachcodec incodecs,

    1. Ifcodec doesnot match any codec incodecCapabilities, throwInvalidModificationError.

  11. Ifcodecs only contains entries for RTX, RED, FEC or Comfort Noise or is an empty set, throwInvalidModificationError. This ensures that we always have something to offer, regardless oftransceiver.direction.

  12. Settransceiver.[[PreferredCodecs]] tocodecs.

Thecodec dictionary match algorithm given twoRTCRtpCodec dictionariesfirst andsecond, and anignoreLevels boolean defaulting tofalse if not specified, is as follows:

  1. Iffirst.mimeType is not anASCII case-insensitive match forsecond.mimeType, returnfalse.

  2. Iffirst.clockRate is different fromsecond.clockRate, returnfalse.

  3. If either (but not both) offirst.channels andsecond.channels aremissing, or if they bothexist andfirst.channels is different fromsecond.channels, returnfalse.

  4. If either (but not both) offirst.sdpFmtpLine andsecond.sdpFmtpLine aremissing, returnfalse.

  5. If bothfirst.sdpFmtpLine andsecond.sdpFmtpLineexist, run the following steps:

    1. If either offirst.sdpFmtpLine andsecond.sdpFmtpLine is not in key-value format, return the result of performing an equals comparison betweenfirst.sdpFmtpLine andsecond.sdpFmtpLine.

    2. LetfirstMediaFormat be a key-value map of the media formats constructed fromfirst.sdpFmtpLine andsecondMediaFormat be a key-value map of the media formats constructed fromsecond.sdpFmtpLine.

      Note

      Which FMTP parameters make up the media format is codec specific. In some cases a parameter can be omitted and still be inferred, in which case it is also a part of the media format of that codec.

    3. IffirstMediaFormat is not equal tosecondMediaFormat, returnfalse.

    4. Candidate Correction 52:Two codecs are considered the same even if level-id is not (PR #3023)

      IfignoreLevels isfalse and the highest complying bitstream levels inferred fromfirst.sdpFmtpLine andsecond.sdpFmtpLine are different, returnfalse.

      Note

      Even ifignoreLevels istrue, some codecs (such as H.264) include levels in the media format, so that ignoring the level requires codec-specific parsing.

  6. Returntrue.

Note

If set, the offerer's receive codec preferences will decide the order of the codecs in the offer. If the answerer does not have any codec preferences then the same order will be used in the answer. However, if the answerer also has codec preferences, these preferences override the order in the answer. In this case, the offerer's preferences would affect which codecs were on offer but not the final order.

5.4.1 Simulcast functionality

Simulcast sending functionality is enabled by theaddTransceiver method via itssendEncodings argument, or thesetRemoteDescription method with a remote offer to receive simulcast, which are both methods on theRTCPeerConnection object. Additionally, thesetParameters method on eachRTCRtpSender object can be used to inspect and modify the functionality.

AnRTCRtpSender'ssimulcast envelope is established in the first successful negotiation that involves it sending simulcast instead of unicast, and includes the maximum number of simulcast streams that can be sent, as well as the ordering of itsencodings. Thissimulcast envelope may be narrowed (reducing the number of layers) in subsequent renegotiation, but cannot be reexpanded. Characteristics of individual simulcast streams can be modified using thesetParameters method, but thesimulcast envelope itself cannot be changed by that method.

One way to configure simulcast is with thesendEncodings option toaddTransceiver(). While theaddTrack() method lacks thesendEncodings argument necessary to configure simulcast, senders can be promoted to simulcast when the user agent is the answerer. Upon calling thesetRemoteDescription method with a remote offer to receive simulcast, aproposed envelope is configured on anRTCRtpSender to contain the layers described in the specified session description. As long as this description isn't rolled back, theproposed envelope becomes theRTCRtpSender'ssimulcast envelope when negotiation completes. As above, thissimulcast envelope may be narrowed in subsequent renegotiation, but not reexpanded.

Candidate Correction 12:Mark RTP Pause/Resume as not supported (PR #2755)

WhilesetParameters cannot modify thesimulcastsimulcastenvelope,, it is still possible to control the number of streams that are sent and the characteristics of those streams. UsingsetParameters, simulcast streams can be made inactive by setting theactive member tofalse, or can be reactivated by setting theactive member totrue. [RFC7728] (RTP Pause/Resume) is not supported, nor is signaling of pause/resume via SDP Offer/Answer.UsingsetParameters, stream characteristics can be changed by modifying attributes such asmaxBitrate.

Note

Simulcast is frequently used to send multiple encodings to an SFU, which will then forward one of the simulcast streams to the end user. The user agent is therefore expected to allocate bandwidth between encodings in such a way that all simulcast streams are usable on their own; for instance, if two simulcast streams have the samemaxBitrate, one would expect to see a similar bitrate on both streams. If bandwidth does not permit all simulcast streams to be sent in an usable form, the user agent is expected to stop sending some of the simulcast streams.

As defined in[RFC9429] (section 3.7.), an offer from a user-agent will only contain a "send" description and no "recv" description on thea=simulcast line. Alternatives and restrictions (described in [RFC8853]) are not supported.

This specification does not define how to configure reception of multiple RTP encodings usingcreateOffer,createAnswer oraddTransceiver. However whensetRemoteDescription is called with a corresponding remote description that is able to send multiple RTP encodings as defined in [RFC9429], and the browser supports receiving multiple RTP encodings, theRTCRtpReceiver may receive multiple RTP encodings and the parameters retrieved via the transceiver'sreceiver.getParameters() will reflect the encodings negotiated.

Note

AnRTCRtpReceiver can receive multiple RTP streams in a scenario where a Selective Forwarding Unit (SFU) switches between simulcast streams it receives from user agents. If the SFU does not rewrite RTP headers so as to arrange the switched streams into a single RTP stream prior to forwarding, theRTCRtpReceiver will receive packets from distinct RTP streams, each with their own SSRC and sequence number space. While the SFU may only forward a single RTP stream at any given time, packets from multiple RTP streams can become intermingled at the receiver due to reordering. AnRTCRtpReceiver equipped to receive multiple RTP streams will therefore need to be able to correctly order the received packets, recognize potential loss events and react to them. Correct operation in this scenario is non-trivial and therefore is optional for implementations of this specification.

5.4.1.1 Encoding Parameter Examples

This section is non-normative.

Examples of simulcast scenarios implemented with encoding parameters:

// Example of 3-layer spatial simulcast with all but the lowest resolution layer disabledvar encodings = [  {rid:'q',active:true,scaleResolutionDownBy:4.0}  {rid:'h',active:false,scaleResolutionDownBy:2.0},  {rid:'f',active:false},];

5.4.2 "Hold" functionality

This section is non-normative.

Together, thedirection attribute and thereplaceTrack method enable developers to implement "hold" scenarios.

To send music to a peer and cease rendering received audio (music-on-hold):

Example 4
asyncfunctionplayMusicOnHold() {try {// Assume we have an audio transceiver and a music track named musicTrackawait audio.sender.replaceTrack(musicTrack);// Mute received audio    audio.receiver.track.enabled =false;// Set the direction to send-only (requires negotiation)    audio.direction ='sendonly';  }catch (err) {console.error(err);  }}

To respond to a remote peer's "sendonly" offer:

Example 5
asyncfunctionhandleSendonlyOffer() {try {// Apply the sendonly offer first,// to ensure the receiver is ready for ICE candidates.await pc.setRemoteDescription(sendonlyOffer);// Stop sending audioawait audio.sender.replaceTrack(null);// Align our direction to avoid further negotiation    audio.direction ='recvonly';// Call createAnswer and send a recvonly answerawaitdoAnswer();  }catch (err) {// handle signaling error  }}

To stop sending music and send audio captured from a microphone, as well to render received audio:

Example 6
asyncfunctionstopOnHoldMusic() {// Assume we have an audio transceiver and a microphone track named micTrackawait audio.sender.replaceTrack(micTrack);// Unmute received audio  audio.receiver.track.enabled =true;// Set the direction to sendrecv (requires negotiation)  audio.direction ='sendrecv';}

To respond to being taken off hold by a remote peer:

Example 7
asyncfunctiononOffHold() {try {// Apply the sendrecv offer first, to ensure receiver is ready for ICE candidates.await pc.setRemoteDescription(sendrecvOffer);// Start sending audioawait audio.sender.replaceTrack(micTrack);// Set the direction sendrecv (just in time for the answer)    audio.direction ='sendrecv';// Call createAnswer and send a sendrecv answerawaitdoAnswer();  }catch (err) {// handle signaling error  }}

5.5RTCDtlsTransport Interface

TheRTCDtlsTransport interface allows an application access to information about the Datagram Transport Layer Security (DTLS) transport over which RTP and RTCP packets are sent and received byRTCRtpSender andRTCRtpReceiver objects, as well other data such as SCTP packets sent and received by data channels. In particular, DTLS adds security to an underlying transport, and theRTCDtlsTransport interface allows access to information about the underlying transport and the security added.RTCDtlsTransport objects are constructed as a result of calls tosetLocalDescription() andsetRemoteDescription(). EachRTCDtlsTransport object represents the DTLS transport layer for the RTP or RTCPcomponent of a specificRTCRtpTransceiver, or a group ofRTCRtpTransceivers if such a group has been negotiated via [RFC8843].

Note
A new DTLS association for an existingRTCRtpTransceiver will be represented by an existingRTCDtlsTransport object, whosestate will be updated accordingly, as opposed to being represented by a new object.

AnRTCDtlsTransport has a[[DtlsTransportState]] internal slot initialized to "new" and a[[RemoteCertificates]] slot initialized to an empty list.

When the underlying DTLS transport experiences an error, such as a certificate validation failure, or a fatal alert (see [RFC5246] section 7.2), the user agentMUST queue a task that runs the following steps:

  1. Lettransport be theRTCDtlsTransport object to receive the state update and error notification.

  2. If the state oftransport is already "failed", abort these steps.

  3. Settransport.[[DtlsTransportState]] to "failed".

  4. Fire an event namederror using theRTCErrorEvent interface with its errorDetail attribute set to either "dtls-failure" or "fingerprint-failure", as appropriate, and other fields set as described under theRTCErrorDetailType enum description, attransport.

  5. Fire an event namedstatechange attransport.

When the underlying DTLS transport needs to update the state of the correspondingRTCDtlsTransport object for any other reason, the user agentMUST queue a task that runs the following steps:

  1. Lettransport be theRTCDtlsTransport object to receive the state update.

  2. LetnewState be the new state.

  3. Settransport.[[DtlsTransportState]] tonewState.

  4. IfnewState isconnected then letnewRemoteCertificates be the certificate chain in use by the remote side, with each certificate encoded in binary Distinguished Encoding Rules (DER) [X690], and settransport.[[RemoteCertificates]] tonewRemoteCertificates.

  5. Fire an event namedstatechange attransport.

WebIDL[Exposed=Window]interfaceRTCDtlsTransport :EventTarget {  [SameObject] readonly attributeRTCIceTransporticeTransport;  readonly attributeRTCDtlsTransportStatestate;sequence<ArrayBuffer>getRemoteCertificates();  attributeEventHandleronstatechange;  attributeEventHandleronerror;};

Attributes

iceTransport of typeRTCIceTransport, readonly

TheiceTransport attribute is the underlying transport that is used to send and receive packets. The underlying transport may not be shared between multiple activeRTCDtlsTransport objects.

state of typeRTCDtlsTransportState, readonly

Thestate attributeMUST, on getting, return the value of the[[DtlsTransportState]] slot.

onstatechange of typeEventHandler
The event type of this event handler isstatechange.
onerror of typeEventHandler
The event type of this event handler iserror.

Methods

getRemoteCertificates

Returns the value of[[RemoteCertificates]].

5.5.1RTCDtlsTransportState Enum

WebIDLenumRTCDtlsTransportState {"new","connecting","connected","closed","failed"};
RTCDtlsTransportState Enumeration description
Enum valueDescription
new DTLS has not started negotiating yet.
connecting DTLS is in the process of negotiating a secure connection and verifying the remote fingerprint.
connected DTLS has completed negotiation of a secure connection and verified the remote fingerprint.
closed The transport has been closed intentionally as the result of receipt of a close_notify alert, or callingclose().
failed The transport has failed as the result of an error (such as receipt of an error alert or failure to validate the remote fingerprint).

5.5.2RTCDtlsFingerprint Dictionary

TheRTCDtlsFingerprint dictionary includes the hash function algorithm and certificate fingerprint as described in [RFC4572].

WebIDLdictionaryRTCDtlsFingerprint {DOMStringalgorithm;DOMStringvalue;};
Dictionary RTCDtlsFingerprint Members
algorithm of typeDOMString

One of the the hash function algorithms defined in the 'Hash function Textual Names' registry [IANA-HASH-FUNCTION].

value of typeDOMString

The value of the certificate fingerprint in lowercase hex string as expressed utilizing the syntax of 'fingerprint' in [RFC4572] Section 5.

5.6RTCIceTransport Interface

TheRTCIceTransport interface allows an application access to information about the ICE transport over which packets are sent and received. In particular, ICE manages peer-to-peer connections which involve state which the application may want to access.RTCIceTransport objects are constructed as a result of calls tosetLocalDescription() andsetRemoteDescription(). The underlying ICE state is managed by theICE agent; as such, the state of anRTCIceTransport changes when theICE Agent provides indications to the user agent as described below. EachRTCIceTransport object represents the ICE transport layer for the RTP or RTCPcomponent of a specificRTCRtpTransceiver, or a group ofRTCRtpTransceivers if such a group has been negotiated via [RFC8843].

Note
An ICE restart for an existingRTCRtpTransceiver will be represented by an existingRTCIceTransport object, whosestate will be updated accordingly, as opposed to being represented by a new object.
Candidate Correction 24:Queue two tasks upon finishing ICE gathering, and fire gatheringstatechange & icegatheringstatechange in same task (PR #2894)

When theICE Agent indicates that it began gathering ageneration of candidates for anRTCIceTransporttransport associated with anRTCPeerConnectionconnection, the user agentMUST queue a task that runs the following steps:

  1. Letconnection be theRTCPeerConnection object associated with thisICE Agent.

  2. Ifconnection.[[IsClosed]] istrue, abort these steps.

  3. Lettransport be theRTCIceTransport for which candidate gathering began.

  4. Settransport.[[IceGathererState]] togathering.

    .

  5. Setconnection.[[IceGatheringState]] to the value of deriving a new state value as described by theRTCIceGatheringState enum.

  6. LetconnectionIceGatheringStateChanged betrue ifconnection.[[IceGatheringState]] changed in the previous step, otherwisefalse.

  7. Do not read or modify state beyond this point.

  8. Fire an event namedgatheringstatechange attransport.

  9. Update the ICE gathering state ofconnection.

  10. IfconnectionIceGatheringStateChanged istrue,fire an event namedicegatheringstatechange atconnection.

When theICE Agent is finished gathering ageneration of candidates for anRTCIceTransporttransport associated with anRTCPeerConnectionconnection, and those candidates have been surfaced to the application, the user agentMUST queue a taskthat runsto runthefollowingfollowingsteps:

  1. Letconnection be theRTCPeerConnection object associated with thisICE Agent.

  2. Ifconnection.[[IsClosed]] istrue, abort these steps.

  3. Lettransport be theRTCIceTransport for which candidate gathering finished.

  4. Ifconnection.[[PendingLocalDescription]] is notnull, and represents the ICEgeneration for which gathering finished, adda=end-of-candidates toconnection.[[PendingLocalDescription]].sdp.

  5. Ifconnection.[[CurrentLocalDescription]] is notnull, and represents the ICEgeneration for which gathering finished, adda=end-of-candidates toconnection.[[CurrentLocalDescription]].sdp.

  6. LetnewCandidateendOfGatheringCandidate be the result ofcreatingananRTCIceCandidate with a new dictionary whosesdpMid andsdpMLineIndex are set to the values associated with thisRTCIceTransport,usernameFragmentisisset to the username fragment of thegeneration of candidates for which gathering finished, andcandidate issetsettoan empty string"".

  7. Fire an event namedicecandidate using theRTCPeerConnectionIceEvent interface with the candidate attribute set tonewCandidateendOfGatheringCandidate atconnection.

  1. If anothergeneration of candidates is still being gathered, abort these steps.

    Note
    This may occur if an ICE restart is initiated while the ICE agent is still gathering the previousgeneration of candidates.
  2. Settransport.[[IceGathererState]] tocomplete.

  3. Fire an event namedgatheringstatechange attransport.

  4. Update the ICE gathering state ofconnection.

When theICE Agent has queued the above task, and no othergenerations of candidates is being gathered, the user agentMUST also queue a second task to run the following steps:

Note
Othergenerations of candidates might still be gathering if an ICE restart was initiated while the ICE agent is still gathering the previousgeneration of candidates.
  1. Ifconnection.[[IsClosed]] istrue, abort these steps.

  2. Settransport.[[IceGathererState]] tocomplete.

  3. Setconnection.[[IceGatheringState]] to the value of deriving a new state value as described by theRTCIceGatheringState enum.

  4. LetconnectionIceGatheringStateChanged betrue ifconnection.[[IceGatheringState]] changed in the previous step, otherwisefalse.

  5. Do not read or modify state beyond this point.

  6. Fire an event namedgatheringstatechange attransport.

  7. IfconnectionIceGatheringStateChanged istrue,fire an event namedicegatheringstatechange atconnection.

  8. Fire an event namedicecandidate using theRTCPeerConnectionIceEvent interface with the candidate attribute set tonull atconnection.

    Note
    The null candidate event is fired to ensure legacy compatibility. New code should monitor the gathering state ofRTCIceTransport and/orRTCPeerConnection.

When theICE Agent indicates that a new ICE candidate is available for anRTCIceTransport, either by taking one from theICE candidate pool or gathering it from scratch, the user agentMUST queue a task that runs the following steps:

  1. Letcandidate be the available ICE candidate.

  2. Letconnection be theRTCPeerConnection object associated with thisICE Agent.

  3. Ifconnection.[[IsClosed]] istrue, abort these steps.

  4. If eitherconnection.[[PendingLocalDescription]] orconnection.[[CurrentLocalDescription]] are notnull, and represent the ICEgeneration for whichcandidate was gathered,surface the candidate withcandidate andconnection, and abort these steps.

  5. Otherwise, appendcandidate toconnection.[[EarlyCandidates]].

When theICE Agent signals that the ICE role has changed due to an ICE binding request with a role collision per [RFC8445] section 7.3.1.1, the UA will queue a task to set the value of[[IceRole]] to the new value.

Torelease early candidates of aconnection, run the following steps:

  1. For each candidate,candidate, inconnection.[[EarlyCandidates]], queue a task tosurface the candidate withcandidate andconnection.

  2. Setconnection.[[EarlyCandidates]] to an empty list.

Tosurface a candidate withcandidate andconnection, run the following steps:

  1. Ifconnection.[[IsClosed]] istrue, abort these steps.

  2. Lettransport be theRTCIceTransport for whichcandidate is being made available.

  3. Ifconnection.[[PendingLocalDescription]] is notnull, and represents the ICEgeneration for whichcandidate was gathered, addcandidate toconnection.[[PendingLocalDescription]].sdp.

  4. Ifconnection.[[CurrentLocalDescription]] is notnull, and represents the ICEgeneration for whichcandidate was gathered, addcandidate toconnection.[[CurrentLocalDescription]].sdp.

  5. LetnewCandidate be the result ofcreating an RTCIceCandidate with a new dictionary whosesdpMid andsdpMLineIndex are set to the values associated with thisRTCIceTransport,usernameFragment is set to the username fragment of the candidate, andcandidate is set to a string encoded using thecandidate-attribute grammar to representcandidate.

  6. AddnewCandidate totransport's set of local candidates.

  7. Fire an event namedicecandidate using theRTCPeerConnectionIceEvent interface with the candidate attribute set tonewCandidate atconnection.

TheRTCIceTransportState of anRTCIceTransport may change because a candidate pair with a usable connection was found and selected or it may change without the selected candidate pair changing. The selected pair andRTCIceTransportState are related and are handled in the same task.

When theICE Agent indicates that anRTCIceTransport has changed either the selected candidate pair, theRTCIceTransportState or both, the user agentMUST queue a task that runs the steps tochange the selected candidate pair and state:

  1. Letconnection be theRTCPeerConnection object associated with thisICE Agent.

  2. Ifconnection.[[IsClosed]] istrue, abort these steps.

  3. Lettransport be theRTCIceTransport whose state is changing.

  4. LetselectedCandidatePairChanged befalse.

  5. LettransportIceConnectionStateChanged befalse.

  6. LetconnectionIceConnectionStateChanged befalse.

  7. LetconnectionStateChanged befalse.

  8. Iftransport's selected candidate pair was changed, run the following steps:

    1. LetnewCandidatePair be the result ofcreating an RTCIceCandidatePair withlocal andremote, representing the local and remote candidates of the indicated pair if one is selected, andnull otherwise.

    2. Settransport.[[SelectedCandidatePair]] tonewCandidatePair.

    3. SetselectedCandidatePairChanged totrue.

  9. Iftransport'sRTCIceTransportState was changed, run the following steps:

    1. Settransport.[[IceTransportState]] to the new indicatedRTCIceTransportState.

    2. SettransportIceConnectionStateChanged totrue.

    3. Setconnection.[[IceConnectionState]] to the value of deriving a new state value as described by theRTCIceConnectionState enum.

    4. Ifconnection.[[IceConnectionState]] changed in the previous step, setconnectionIceConnectionStateChanged totrue.

    5. Setconnection.[[ConnectionState]] to the value of deriving a new state value as described by theRTCPeerConnectionState enum.

    6. Ifconnection.[[ConnectionState]] changed in the previous step, setconnectionStateChanged totrue.

  10. IfselectedCandidatePairChanged istrue,fire an event namedselectedcandidatepairchange attransport.

  11. IftransportIceConnectionStateChanged istrue,fire an event namedstatechange attransport.

  12. IfconnectionIceConnectionStateChanged istrue,fire an event namediceconnectionstatechange atconnection.

  13. IfconnectionStateChanged istrue,fire an event namedconnectionstatechange atconnection.

AnRTCIceTransport object has the following internal slots:

WebIDL[Exposed=Window]interfaceRTCIceTransport :EventTarget {  readonly attributeRTCIceRolerole;  readonly attributeRTCIceComponentcomponent;  readonly attributeRTCIceTransportStatestate;  readonly attributeRTCIceGathererStategatheringState;sequence<RTCIceCandidate>getLocalCandidates();sequence<RTCIceCandidate>getRemoteCandidates();RTCIceCandidatePair?getSelectedCandidatePair();RTCIceParameters?getLocalParameters();RTCIceParameters?getRemoteParameters();  attributeEventHandleronstatechange;  attributeEventHandlerongatheringstatechange;  attributeEventHandleronselectedcandidatepairchange;};

Attributes

role of typeRTCIceRole, readonly

Therole attributeMUST, on getting, return the value of the [[IceRole]] internal slot.

component of typeRTCIceComponent, readonly

Thecomponent attributeMUST return the ICE component of the transport. When RTCP mux is used, a singleRTCIceTransport transports both RTP and RTCP andcomponent is set to "rtp".

state of typeRTCIceTransportState, readonly

Thestate attributeMUST, on getting, return the value of the[[IceTransportState]] slot.

gatheringState of typeRTCIceGathererState, readonly

ThegatheringState attributeMUST, on getting, return the value of the[[IceGathererState]] slot.

onstatechange of typeEventHandler
This event handler, of event handler event typestatechange,MUST be fired any time theRTCIceTransportstate changes.
ongatheringstatechange of typeEventHandler
This event handler, of event handler event typegatheringstatechange,MUST be fired any time theRTCIceTransport's[[IceGathererState]] changes.
onselectedcandidatepairchange of typeEventHandler
This event handler, of event handler event typeselectedcandidatepairchange,MUST be fired any time theRTCIceTransport's selected candidate pair changes.

Methods

getLocalCandidates

Returns a sequence describing the local ICE candidates gathered for thisRTCIceTransport and sent inonicecandidate.

getRemoteCandidates

Returns a sequence describing the remote ICE candidates received by thisRTCIceTransport viaaddIceCandidate().

Note
getRemoteCandidates will not expose peer reflexive candidates since they are not received viaaddIceCandidate().
getSelectedCandidatePair

Returns the selected candidate pair on which packets are sent. This methodMUST return the value of the[[SelectedCandidatePair]] slot. WhenRTCIceTransport.state is "new" or "closed"getSelectedCandidatePair returnsnull.

getLocalParameters

Returns the local ICE parameters received by thisRTCIceTransport viasetLocalDescription, ornull if the parameters have not yet been received.

getRemoteParameters

Returns the remote ICE parameters received by thisRTCIceTransport viasetRemoteDescription ornull if the parameters have not yet been received.

5.6.1RTCIceParameters Dictionary

WebIDLdictionaryRTCIceParameters {DOMStringusernameFragment;DOMStringpassword;};
DictionaryRTCIceParameters Members
usernameFragment of typeDOMString

The ICE username fragment as defined in [RFC5245], Section 7.1.2.3.

password of typeDOMString

The ICE password as defined in [RFC5245], Section 7.1.2.3.

Candidate Addition 45:Convert RTCIceCandidatePair dictionary to an interface (PR #2961)

5.6.2RTCIceCandidatePair Dictionary

5.6.2RTCIceCandidatePair Interface

This interface represents an ICE candidate pair, described in Section 4 in [RFC8445]. AnRTCIceCandidatePair is a pairing of a local and a remoteRTCIceCandidate.

Tocreate an RTCIceCandidatePair withRTCIceCandidate objects,local andremote, run the following steps:

  1. LetcandidatePair be a newly createdRTCIceCandidatePair object.
  2. LetcandidatePair have a[[Local]] internal slot, initialized tolocal.
  3. LetcandidatePair have a[[Remote]] internal slot, initialized toremote.
  4. ReturncandidatePair.
dictionary[Exposed=Window]interfaceRTCIceCandidatePair {[SameObject] readonly attributeRTCIceCandidate local;[SameObject] readonly attributeRTCIceCandidate remote;};
DictionaryRTCIceCandidatePair Members
Attributes
local of typeRTCIceCandidate, readonly

The local ICE candidate.

Thelocal attributeMUST, on getting, return the value of the[[Local]] internal slot.

remote of typeRTCIceCandidate, readonly

The remote ICE candidate.

Theremote attributeMUST, on getting, return the value of the[[Remote]] internal slot.

5.6.3RTCIceGathererState Enum

WebIDLenumRTCIceGathererState {"new","gathering","complete"};
RTCIceGathererState Enumeration description
Enum valueDescription
new TheRTCIceTransport was just created, and has not started gathering candidates yet.
gathering TheRTCIceTransport is in the process of gathering candidates.
complete TheRTCIceTransport has completed gathering and the end-of-candidates indication for this transport has been sent. It will not gather candidates again until an ICE restart causes it to restart.

5.6.4RTCIceTransportState Enum

WebIDLenumRTCIceTransportState {"closed","failed","disconnected","new","checking","completed","connected"};
RTCIceTransportState Enumeration description
Enum valueDescription
closed TheRTCIceTransport has shut down and is no longer responding to STUN requests.
failed
TheRTCIceTransport has finished gathering, received an indication that there are no more remote candidates, finished checking all candidate pairs, and all pairs have either failed connectivity checks or lost consent, and either zero local candidates were gathered or the PAC timer has expired [RFC8863]. This is a terminal state until ICE is restarted. Since an ICE restart may cause connectivity to resume, entering the "failed" state does not cause DTLS transports, SCTP associations or the data channels that run over them to close, or tracks to mute.
disconnected TheICE Agent has determined that connectivity is currently lost for thisRTCIceTransport. This is a transient state that may trigger intermittently (and resolve itself without action) on a flaky network. The way this state is determined is implementation dependent. Examples include:
  • Losing the network interface for the connection in use.
  • Repeatedly failing to receive a response to STUN requests.
Alternatively, theRTCIceTransport has finished checking all existing candidates pairs and not found a connection (or consent checks [RFC7675] once successful, have now failed), but it is still gathering and/or waiting for additional remote candidates.
new TheRTCIceTransport is gathering candidates and/or waiting for remote candidates to be supplied, and has not yet started checking.
checking TheRTCIceTransport has received at least one remote candidate (by means ofaddIceCandidate() or discovered as a peer-reflexive candidate when receiving a STUN binding request) and is checking candidate pairs and has either not yet found a connection or consent checks [RFC7675] have failed on all previously successful candidate pairs. In addition to checking, it may also still be gathering.
completed TheRTCIceTransport has finished gathering, received an indication that there are no more remote candidates, finished checking all candidate pairs and found a connection. If consent checks [RFC7675] subsequently fail on all successful candidate pairs, the state transitions to "failed".
connected TheRTCIceTransport has found a usable connection, but is still checking other candidate pairs to see if there is a better connection. It may also still be gathering and/or waiting for additional remote candidates. If consent checks [RFC7675] fail on the connection in use, and there are no other successful candidate pairs available, then the state transitions to "checking" (if there are candidate pairs remaining to be checked) or "disconnected" (if there are no candidate pairs to check, but the peer is still gathering and/or waiting for additional remote candidates).
Note

The most common transitions for a successful call will be new -> checking -> connected -> completed, but under specific circumstances (only the last checked candidate succeeds, and gathering and the no-more candidates indication both occur prior to success), the state can transition directly from "checking" to "completed".

An ICE restart causes candidate gathering and connectivity checks to begin anew, causing a transition to "connected" if begun in the "completed" state. If begun in the transient "disconnected" state, it causes a transition to "checking", effectively forgetting that connectivity was previously lost.

The "failed" and "completed" states require an indication that there are no additional remote candidates. This can be indicated by callingaddIceCandidate with a candidate value whosecandidate property is set to an empty string or bycanTrickleIceCandidates being set tofalse.

Some example state transitions are:

ICE transport state transition diagram
Figure2 Non-normative ICE transport state transition diagram

5.6.5RTCIceRole Enum

WebIDLenumRTCIceRole {"unknown","controlling","controlled"};
RTCIceRole Enumeration description
Enum valueDescription
unknown An agent whose role as defined by [RFC5245], Section 3, has not yet been determined.
controlling A controlling agent as defined by [RFC5245], Section 3.
controlled A controlled agent as defined by [RFC5245], Section 3.

5.6.6RTCIceComponent Enum

WebIDLenumRTCIceComponent {"rtp","rtcp"};
RTCIceComponent Enumeration description
Enum valueDescription
rtp The ICE Transport is used for RTP (or RTCP multiplexing), as defined in [RFC5245], Section 4.1.1.1. Protocols multiplexed with RTP (e.g. data channel) share its component ID. This represents thecomponent-id value1 when encoded incandidate-attribute.
rtcp The ICE Transport is used for RTCP as defined by [RFC5245], Section 4.1.1.1. This represents thecomponent-id value2 when encoded incandidate-attribute.

5.7RTCTrackEvent

Thetrack event uses theRTCTrackEvent interface.

WebIDL[Exposed=Window]interfaceRTCTrackEvent :Event {constructor(DOMStringtype,RTCTrackEventIniteventInitDict);  readonly attributeRTCRtpReceiverreceiver;  readonly attributeMediaStreamTracktrack;  [SameObject] readonly attributeFrozenArray<MediaStream>streams;  readonly attributeRTCRtpTransceivertransceiver;};

Constructors

RTCTrackEvent.constructor()

Attributes

receiver of typeRTCRtpReceiver, readonly

Thereceiver attribute represents theRTCRtpReceiver object associated with the event.

track of typeMediaStreamTrack, readonly

Thetrack attribute represents theMediaStreamTrack object that is associated with theRTCRtpReceiver identified byreceiver.

streams of typeFrozenArray<MediaStream>, readonly

Thestreams attribute returns an array ofMediaStream objects representing theMediaStreams that this event'strack is a part of.

transceiver of typeRTCRtpTransceiver, readonly

Thetransceiver attribute represents theRTCRtpTransceiver object associated with the event.

WebIDLdictionaryRTCTrackEventInit :EventInit {  requiredRTCRtpReceiverreceiver;  requiredMediaStreamTracktrack;sequence<MediaStream>streams = [];  requiredRTCRtpTransceivertransceiver;};

DictionaryRTCTrackEventInit Members

receiver of typeRTCRtpReceiver, required

Thereceiver member represents theRTCRtpReceiver object associated with the event.

track of typeMediaStreamTrack, required

Thetrack member represents theMediaStreamTrack object that is associated with theRTCRtpReceiver identified byreceiver.

streams of typesequence<MediaStream>, defaulting to[]

Thestreams member is an array ofMediaStream objects representing theMediaStreams that this event'strack is a part of.

transceiver of typeRTCRtpTransceiver, required

Thetransceiver attribute represents theRTCRtpTransceiver object associated with the event.

6. Peer-to-peer Data API

The Peer-to-peer Data API lets a web application send and receive generic application data peer-to-peer. The API for sending and receiving data models the behavior ofWeb Sockets.

6.1 RTCPeerConnection Interface Extensions

The Peer-to-peer data API extends theRTCPeerConnection interface as described below.

WebIDL          partial interfaceRTCPeerConnection {  readonly attributeRTCSctpTransport?sctp;RTCDataChannelcreateDataChannel(USVStringlabel,                                   optionalRTCDataChannelInitdataChannelDict = {});  attributeEventHandlerondatachannel;};

Attributes

sctp of typeRTCSctpTransport, readonly, nullable

The SCTP transport over which SCTP data is sent and received. If SCTP has not been negotiated, the value is null. This attributeMUST return theRTCSctpTransport object stored in the[[SctpTransport]] internal slot.

ondatachannel of typeEventHandler
The event type of this event handler isdatachannel.

Methods

createDataChannel

Creates a newRTCDataChannel object with the given label. TheRTCDataChannelInit dictionary can be used to configure properties of the underlying channel such as data reliability.

When thecreateDataChannel method is invoked, the user agentMUST run the following steps.

  1. Letconnection be theRTCPeerConnection object on which the method is invoked.

  2. Ifconnection.[[IsClosed]] istrue,throw anInvalidStateError.

  3. Create an RTCDataChannel,channel.

  4. Initializechannel.[[DataChannelLabel]] to the value of the first argument.

  5. If the UTF-8 representation of[[DataChannelLabel]] is longer than 65535 bytes,throw aTypeError.

  6. Letoptions be the second argument.

  7. Initializechannel.[[MaxPacketLifeTime]] tooption.maxPacketLifeTime, if present, otherwisenull.

  8. Initializechannel.[[MaxRetransmits]] tooption.maxRetransmits, if present, otherwisenull.

  9. Initializechannel.[[Ordered]] tooption.ordered.

  10. Initializechannel.[[DataChannelProtocol]] tooption.protocol.

  11. If the UTF-8 representation of[[DataChannelProtocol]] is longer than 65535 bytes,throw aTypeError.

  12. Initializechannel.[[Negotiated]] tooption.negotiated.

  13. Initializechannel.[[DataChannelId]] to the value ofoption.id, if it is present and[[Negotiated]] is true, otherwisenull.

    Note
    This means theid member will be ignored if the data channel is negotiated in-band; this is intentional. Data channels negotiated in-band should have IDs selected based on the DTLS role, as specified in [RFC8832].
  14. If[[Negotiated]] istrue and[[DataChannelId]] isnull,throw aTypeError.

  15. If both[[MaxPacketLifeTime]] and[[MaxRetransmits]] attributes are set (not null),throw aTypeError.

  16. If a setting, either[[MaxPacketLifeTime]] or[[MaxRetransmits]], has been set to indicate unreliable mode, and that value exceeds the maximum value supported by the user agent, the valueMUST be set to the user agents maximum value.

  17. If[[DataChannelId]] is equal to 65535, which is greater than the maximum allowed ID of 65534 but still qualifies as anunsigned short,throw aTypeError.

  18. If the[[DataChannelId]] slot isnull (due to no ID being passed intocreateDataChannel, or[[Negotiated]] being false), and the DTLS role of the SCTP transport has already been negotiated, then initialize[[DataChannelId]] to a value generated by the user agent, according to [RFC8832], and skip to the next step. If no available ID could be generated, or if the value of the[[DataChannelId]] slot is being used by an existingRTCDataChannel,throw anOperationError exception.

    Note
    If the[[DataChannelId]] slot isnull after this step, it will be populated during theRTCSctpTransport connected procedure.
  19. Lettransport beconnection.[[SctpTransport]].

    If the[[DataChannelId]] slot is notnull,transport is in the "connected" state and[[DataChannelId]] is greater or equal totransport.[[MaxChannels]],throw anOperationError.

  20. Ifchannel is the firstRTCDataChannel created onconnection,update the negotiation-needed flag forconnection.

  21. Appendchannel toconnection.[[DataChannels]].

  22. Returnchannel and continue the following stepsin parallel.

  23. Createchannel's associatedunderlying data transport and configure it according to the relevant properties ofchannel.

6.1.1RTCSctpTransport Interface

TheRTCSctpTransport interface allows an application access to information about the SCTP data channels tied to a particular SCTP association.

6.1.1.1 Create an instance

Tocreate anRTCSctpTransport with an initial state,initialState, run the following steps:

  1. Lettransport be a newRTCSctpTransport object.

  2. Lettransport have a[[SctpTransportState]] internal slot initialized toinitialState.

  3. Lettransport have a[[MaxMessageSize]] internal slot and run the steps labeledupdate the data max message size to initialize it.

  4. Lettransport have a[[MaxChannels]] internal slot initialized tonull.

  5. Returntransport.

6.1.1.2 Update max message size

Toupdate the data max message size of anRTCSctpTransport run the following steps:

  1. Lettransport be theRTCSctpTransport object to be updated.

  2. LetremoteMaxMessageSize be the value of themax-message-size SDP attribute read from the remote description, as described in [RFC8841] (section 6), or 65536 if the attribute is missing.

  3. LetcanSendSize be the number of bytes that this client can send (i.e. the size of the local send buffer) or 0 if the implementation can handle messages of any size.

  4. If bothremoteMaxMessageSize andcanSendSize are 0, set[[MaxMessageSize]] to the positive Infinity value.

  5. Else, if eitherremoteMaxMessageSize orcanSendSize is 0, set[[MaxMessageSize]] to the larger of the two.

  6. Else, set[[MaxMessageSize]] to the smaller ofremoteMaxMessageSize orcanSendSize.

6.1.1.3 Connected procedure

Once anSCTP transport is connected, meaning the SCTP association of anRTCSctpTransport has been established, the user agentMUSTqueue a task that runs the following steps:

  1. Lettransport be theRTCSctpTransport object.

  2. Letconnection be theRTCPeerConnection object associated withtransport.

  3. Set[[MaxChannels]] to the minimum of the negotiated amount of incoming and outgoing SCTP streams.

  4. For each ofconnection'sRTCDataChannel:

    1. Letchannel be theRTCDataChannel object.

    2. Ifchannel.[[DataChannelId]] isnull, initialize[[DataChannelId]] to the value generated by the underlying sctp data channel, according to [RFC8832].

    3. Ifchannel.[[DataChannelId]] is greater or equal totransport.[[MaxChannels]], or the previous step failed to assign an id,close thechannel due to a failure. Otherwise,announce the channel as open.

  5. Fire an event namedstatechange attransport.

    Note

    This event is fired before theopen events fired byannouncing the channel as open; theopen events are fired from a separate queued task.

WebIDL[Exposed=Window]interfaceRTCSctpTransport :EventTarget {  readonly attributeRTCDtlsTransporttransport;  readonly attributeRTCSctpTransportStatestate;  readonly attributeunrestricted doublemaxMessageSize;  readonly attributeunsigned short?maxChannels;  attributeEventHandleronstatechange;};
Attributes
transport of typeRTCDtlsTransport, readonly

The transport over which all SCTP packets for data channels will be sent and received.

state of typeRTCSctpTransportState, readonly

The current state of the SCTP transport. On getting, this attributeMUST return the value of the[[SctpTransportState]] slot.

maxMessageSize of typeunrestricted double, readonly

The maximum size of data that can be passed toRTCDataChannel'ssend() method. The attributeMUST, on getting, return the value of the[[MaxMessageSize]] slot.

maxChannels of typeunsigned short , readonly, nullable

The maximum amount ofRTCDataChannel's that can be used simultaneously. The attributeMUST, on getting, return the value of the[[MaxChannels]] slot.

Note
This attribute's value will benull until the SCTP transport goes into the "connected" state.
onstatechange of typeEventHandler

The event type of this event handler isstatechange.

6.1.2RTCSctpTransportState Enum

RTCSctpTransportState indicates the state of the SCTP transport.

WebIDLenumRTCSctpTransportState {"connecting","connected","closed"};
RTCSctpTransportState Enumeration description
Enum valueDescription
connecting

TheRTCSctpTransport is in the process of negotiating an association. This is the initial state of the [[SctpTransportState]] slot when anRTCSctpTransport is created.

connected

When the negotiation of an association is completed, a task is queued to update the [[SctpTransportState]] slot to "connected".

closed

A task is queued to update the [[SctpTransportState]] slot to "closed" when:

  • a SHUTDOWN or ABORT chunk is received.
  • the SCTP association has been closed intentionally, such as by closing the peer connection or applying a remote description that rejects data or changes the SCTP port.
  • the underlying DTLS association has transitioned to "closed" state.

Note that the last transition is logical due to the fact that an SCTP association requires an established DTLS connection - [RFC8261] section 6.1 specifies that SCTP over DTLS is single-homed - and that no way of of switching to an alternate transport is defined in this API.

6.2RTCDataChannel

TheRTCDataChannel interface represents a bi-directional data channel between two peers. AnRTCDataChannel is created via a factory method on anRTCPeerConnection object. The messages sent between the browsers are described in [RFC8831] and [RFC8832].

There are two ways to establish a connection withRTCDataChannel. The first way is to simply create anRTCDataChannel at one of the peers with thenegotiatedRTCDataChannelInit dictionary member unset or set to its default value false. This will announce the new channel in-band and trigger anRTCDataChannelEvent with the correspondingRTCDataChannel object at the other peer. The second way is to let the application negotiate theRTCDataChannel. To do this, create anRTCDataChannel object with thenegotiatedRTCDataChannelInit dictionary member set to true, and signal out-of-band (e.g. via a web server) to the other side that itSHOULD create a correspondingRTCDataChannel with thenegotiatedRTCDataChannelInit dictionary member set to true and the sameid. This will connect the two separately createdRTCDataChannel objects. The second way makes it possible to create channels with asymmetric properties and to create channels in a declarative way by specifying matchingids.

EachRTCDataChannel has an associatedunderlying data transport that is used to transport actual data to the other peer. In the case of SCTP data channels utilizing anRTCSctpTransport (which represents the state of the SCTP association), the underlying data transport is the SCTP stream pair. The transport properties of theunderlying data transport, such as in order delivery settings and reliability mode, are configured by the peer as the channel is created. The properties of a channel cannot change after the channel has been created. The actual wire protocol between the peers is specified by the WebRTC DataChannel Protocol specification [RFC8831].

AnRTCDataChannel can be configured to operate in different reliability modes. A reliable channel ensures that the data is delivered at the other peer through retransmissions. An unreliable channel is configured to either limit the number of retransmissions (maxRetransmits ) or set a time during which transmissions (including retransmissions) are allowed (maxPacketLifeTime ). These properties can not be used simultaneously and an attempt to do so will result in an error. Not setting any of these properties results in a reliable channel.

AnRTCDataChannel, created withcreateDataChannel or dispatched via anRTCDataChannelEvent,MUST initially be in the "connecting" state. When theRTCDataChannel object'sunderlying data transport is ready, the user agentMUSTannounce the RTCDataChannel as open.

6.2.1 Creating a data channel

Tocreate anRTCDataChannel, run the following steps:

  1. Letchannel be a newly createdRTCDataChannel object.

  2. Letchannel have a[[ReadyState]] internal slot initialized to "connecting".

  3. Letchannel have a[[BufferedAmount]] internal slot initialized to0.

  4. Letchannel have internal slots named[[DataChannelLabel]],[[Ordered]],[[MaxPacketLifeTime]],[[MaxRetransmits]],[[DataChannelProtocol]],[[Negotiated]], and[[DataChannelId]].

  5. Letchannel have a[[IsTransferable]] internal slot initialized totrue.
  6. Queue a task to run the following step:
    1. Setchannel.[[IsTransferable]] tofalse.

    This task needs to run before any task enqueued by thereceiving messages on a data channel algorithm forchannel.This ensures that no message is lost during the transfer of aRTCDataChannel.

  7. Returnchannel.

6.2.2 Announcing a data channel as open

When the user agent is toannounce anRTCDataChannel as open, the user agentMUST queue a task to run the following steps:

  1. If the associatedRTCPeerConnection object's[[IsClosed]] slot istrue, abort these steps.

  2. Letchannel be theRTCDataChannel object to be announced.

  3. Ifchannel.[[ReadyState]] is "closing" or "closed", abort these steps.

  4. Setchannel.[[ReadyState]] to "open".

  5. Fire an event namedopen atchannel.

6.2.3 Announcing a data channel instance

When anunderlying data transport is to be announced (the other peer created a channel withnegotiated unset or set to false), the user agent of the peer that did not initiate the creation processMUST queue a task to run the following steps:

  1. Letconnection be theRTCPeerConnection object associated with theunderlying data transport.

  2. Ifconnection.[[IsClosed]] istrue, abort these steps.

  3. Create an RTCDataChannel,channel.

  4. Letconfiguration be an information bundle received from the other peer as a part of the process to establish theunderlying data transport described by the WebRTC DataChannel Protocol specification [RFC8832].

  5. Initializechannel.[[DataChannelLabel]],[[Ordered]],[[MaxPacketLifeTime]],[[MaxRetransmits]],[[DataChannelProtocol]], and[[DataChannelId]] internal slots to the corresponding values inconfiguration.

  6. Initializechannel.[[Negotiated]] tofalse.

  7. Appendchannel toconnection.[[DataChannels]].

  8. Setchannel.[[ReadyState]] to "open" (but do not fire theopen event, yet).

    Note
    This allows to start sending messages inside of thedatachannel event handler prior to theopen event being fired.
  9. Fire an event nameddatachannel using theRTCDataChannelEvent interface with thechannel attribute set tochannel atconnection.

  10. Announce the data channel as open.

Candidate Correction 38:Prevent GC of non-closed RTCDataChannels (PR #2902)

6.2.4 Closing procedure

6.2.4 Closing procedure

AnRTCDataChannel object'sunderlying data transport may be torn down in a non-abrupt manner by running theclosing procedure. When that happens the user agentMUST queue a task to run the following steps:

  1. Letchannel be theRTCDataChannel object whoseunderlying data transport was closed.

  2. Letconnection be theRTCPeerConnection object associated withchannel.

  3. Removechannel fromconnection.[[DataChannels]].

  4. Unless the procedure was initiated bychannel.close, setchannel.[[ReadyState]] to "closing" andfire an event namedclosing atchannel.

  5. Run the following stepsin parallelin parallel:

    1. Finish sending all currently pending messages of thechannel.

    2. Follow the closing procedure defined for thechannel'sunderlying data transport :

      1. In the case of an SCTP-basedtransport, follow [RFC8831], section 6.7.

    3. RenderClosethechannel'sdata transportclosedby following the associated procedure.

6.2.5Announcing a data channel as closed

When anRTCDataChannel object'sunderlying data transport has beenclosed, the user agentMUST queue a task to run the following steps:

  1. Letchannel be theRTCDataChannel object whoseunderlying data transport was closed.

  2. Ifchannel.[[ReadyState]] is "closed", abort these steps.
  3. Setchannel.[[ReadyState]] to "closed".

  4. Removechannel fromconnection.[[DataChannels]] if it is still there.

  5. If thetransport was closedwith an error,fire an event namederror using theRTCErrorEvent interface with itserrorDetail attribute set to "sctp-failure" atchannel.

  6. Fire an event namedclose atchannel.

6.2.6Transfering data channel

TheRTCDataChanneltransfer steps, givenvalue anddataHolder, are:

  1. Ifvalue.[[IsTransferable]] isfalse, throw aDataCloneError DOMException.

  2. SetdataHolder.[[ReadyState]] tovalue.[[ReadyState]].

  3. SetdataHolder.[[DataChannelLabel]] tovalue.[[DataChannelLabel]].

  4. SetdataHolder.[[Ordered]] tovalue.[[Ordered]].

  5. SetdataHolder.[[MaxPacketLifeTime]] tovalue..[[MaxPacketLifeTime]]

  6. SetdataHolder.[[MaxRetransmits]] tovalue.[[MaxRetransmits]].

  7. SetdataHolder.[[DataChannelProtocol]] tovalue.[[DataChannelProtocol]].

  8. SetdataHolder.[[Negotiated]] tovalue.[[Negotiated]].

  9. SetdataHolder.[[DataChannelId]] tovalue.[[DataChannelId]].

  10. SetdataHolder’sunderlying data transport tovalueunderlying data transport.

  11. Setvalue.[[IsTransferable]] tofalse.

  12. Setvalue.[[ReadyState]] to "closed".

TheRTCDataChanneltransfer-receiving steps, givendataHolder andchannel, are:

  1. Initializechannel.[[ReadyState]] todataHolder.[[ReadyState]].

  2. Initializechannel.[[DataChannelLabel]] todataHolder.[[DataChannelLabel]].

  3. Initializechannel.[[Ordered]] todataHolder.[[Ordered]].

  4. Initializechannel.[[MaxPacketLifeTime]] todataHolder.[[MaxPacketLifeTime]].

  5. Initializechannel.[[MaxRetransmits]] todataHolder.[[MaxRetransmits]].

  6. Initializechannel.[[DataChannelProtocol]] todataHolder.[[DataChannelProtocol]].

  7. Initializechannel.[[Negotiated]] todataHolder.[[Negotiated]].

  8. Initializechannel.[[DataChannelId]] todataHolder.[[DataChannelId]].

  9. Initializechannel’sunderlying data transport todataHolder’sunderlying data transport.

The above steps do not need to transfer[[BufferedAmount]] as its value will always be equal to0. The reason is anRTCDataChannel can be transferred only if itssend() algorithm was not called prior the transfer.

If theunderlying data transport is closed at the time of thetransfer-receiving steps, theRTCDataChannel object will be closed by running theannouncing a data channel as closed algorithm immediately after thetransfer-receiving steps.

6.2.7 Error on creating data channels

In some cases, the user agent may beunable to create anRTCDataChannel 'sunderlying data transport. For example, the data channel'sid may be outside the range negotiated by the [RFC8831] implementations in the SCTP handshake. When the user agent determines that anRTCDataChannel'sunderlying data transport cannot be created, the user agentMUST queue a task to run the following steps:

  1. Letchannel be theRTCDataChannel object for which the user agent could not create anunderlying data transport.

  2. Setchannel.[[ReadyState]] to "closed".

  3. Fire an event namederror using theRTCErrorEvent interface with theerrorDetail attribute set to "data-channel-failure" atchannel.

  4. Fire an event namedclose atchannel.

6.2.8Receiving messages on a data channel

When anRTCDataChannel message has been received via theunderlying data transport with typetype and datarawData, the user agentMUST queue a task to run the following steps:

  1. Letchannel be theRTCDataChannel object for which the user agent has received a message.

  2. Letconnection be theRTCPeerConnection object associated withchannel.

  3. Ifchannel.[[ReadyState]] is not "open", abort these steps and discardrawData.

  4. Execute the sub step by switching ontype andchannel.binaryType:

    • Iftype indicates thatrawData is astring:

      Letdata be aDOMString that represents the result of decodingrawData as UTF-8.

    • Iftype indicates thatrawData is binary andbinaryType is"blob":

      Letdata be a newBlob object containingrawData as its raw data source.

    • Iftype indicates thatrawData is binary andbinaryType is"arraybuffer":

      Letdata be a newArrayBuffer object containingrawData as its raw data source.

  5. Fire an event namedmessage using theMessageEvent interface with itsorigin attribute initialized to theserialization of an origin ofconnection.[[DocumentOrigin]], and thedata attribute initialized todata atchannel.

WebIDL[Exposed=(Window,DedicatedWorker),Transferable]interfaceRTCDataChannel :EventTarget {  readonly attributeUSVStringlabel;  readonly attributebooleanordered;  readonly attributeunsigned short?maxPacketLifeTime;  readonly attributeunsigned short?maxRetransmits;  readonly attributeUSVStringprotocol;  readonly attributebooleannegotiated;  readonly attributeunsigned short?id;  readonly attributeRTCDataChannelStatereadyState;  readonly attributeunsigned longbufferedAmount;  [EnforceRange] attributeunsigned longbufferedAmountLowThreshold;  attributeEventHandleronopen;  attributeEventHandleronbufferedamountlow;  attributeEventHandleronerror;  attributeEventHandleronclosing;  attributeEventHandleronclose;undefinedclose();  attributeEventHandleronmessage;  attributeBinaryTypebinaryType;undefinedsend(USVStringdata);undefinedsend(Blobdata);undefinedsend(ArrayBufferdata);undefinedsend(ArrayBufferViewdata);};

Attributes

label of typeUSVString, readonly

Thelabel attribute represents a label that can be used to distinguish thisRTCDataChannel object from otherRTCDataChannel objects. Scripts are allowed to create multipleRTCDataChannel objects with the same label. On getting, the attributeMUST return the value of the[[DataChannelLabel]] slot.

ordered of typeboolean, readonly

Theordered attribute returns true if theRTCDataChannel is ordered, and false if out of order delivery is allowed. On getting, the attributeMUST return the value of the[[Ordered]] slot.

maxPacketLifeTime of typeunsigned short, readonly, nullable

ThemaxPacketLifeTime attribute returns the length of the time window (in milliseconds) during which transmissions and retransmissions may occur in unreliable mode. On getting, the attributeMUST return the value of the[[MaxPacketLifeTime]] slot.

maxRetransmits of typeunsigned short, readonly, nullable

ThemaxRetransmits attribute returns the maximum number of retransmissions that are attempted in unreliable mode. On getting, the attributeMUST return the value of the[[MaxRetransmits]] slot.

protocol of typeUSVString, readonly

Theprotocol attribute returns the name of the sub-protocol used with thisRTCDataChannel. On getting, the attributeMUST return the value of the[[DataChannelProtocol]] slot.

negotiated of typeboolean, readonly

Thenegotiated attribute returns true if thisRTCDataChannel was negotiated by the application, or false otherwise. On getting, the attributeMUST return the value of the[[Negotiated]] slot.

id of typeunsigned short, readonly, nullable

Theid attribute returns the ID for thisRTCDataChannel. The value is initially null, which is what will be returned if the ID was not provided at channel creation time, and the DTLS role of the SCTP transport has not yet been negotiated. Otherwise, it will return the ID that was either selected by the script or generated by the user agent according to [RFC8832]. After the ID is set to a non-null value, it will not change. On getting, the attributeMUST return the value of the[[DataChannelId]] slot.

readyState of typeRTCDataChannelState, readonly

ThereadyState attribute represents the state of theRTCDataChannel object. On getting, the attributeMUST return the value of the[[ReadyState]] slot.

bufferedAmount of typeunsigned long, readonly

ThebufferedAmount attributeMUST, on getting, return the value of the[[BufferedAmount]] slot. The attribute exposes the number of bytes of application data (UTF-8 text and binary data) that have been queued usingsend(). Even though the data transmission can occurin parallel, the returned valueMUST NOT be decreased before the current task yielded back to the event loop to prevent race conditions. The value does not include framing overhead incurred by the protocol, or buffering done by the operating system or network hardware. The value of the[[BufferedAmount]] slot will only increase with each call to thesend() method as long as the[[ReadyState]] slot is "open"; however, the slot does not reset to zero once the channel closes. When theunderlying data transport sends data from its queue, the user agentMUST queue a task that reduces[[BufferedAmount]] with the number of bytes that was sent.

bufferedAmountLowThreshold of typeunsigned long

ThebufferedAmountLowThreshold attribute sets the threshold at which thebufferedAmount is considered to be low. When thebufferedAmount decreases from above this threshold to equal or below it, thebufferedamountlow event fires. ThebufferedAmountLowThreshold is initially zero on each newRTCDataChannel, but the application may change its value at any time.

onopen of typeEventHandler
The event type of this event handler isopen.
onbufferedamountlow of typeEventHandler
The event type of this event handler isbufferedamountlow.
onerror of typeEventHandler

The event type of this event handler isRTCErrorEvent.errorDetail contains "sctp-failure",sctpCauseCode contains the SCTP Cause Code value, andmessage contains the SCTP Cause-Specific-Information, possibly with additional text.

onclosing of typeEventHandler

The event type of this event handler isclosing.

onclose of typeEventHandler

The event type of this event handler isclose.

onmessage of typeEventHandler

The event type of this event handler ismessage.

binaryType of typeBinaryType

ThebinaryType attribute returns the value to which it was last set.When anRTCDataChannel object is created, thebinaryType attributeMUST be initialized to the string "arraybuffer".

This attribute controls how binary data is exposed to scripts. See Web Socket'sbinaryType.

Methods

close()

Closes theRTCDataChannel. It may be called regardless of whether theRTCDataChannel object was created by this peer or the remote peer.

When theclose method is called, the user agentMUST run the following steps:

  1. Letchannel be theRTCDataChannel object which is about to be closed.

  2. Ifchannel.[[ReadyState]] is "closing" or "closed", then abort these steps.

  3. Setchannel.[[ReadyState]] to "closing".

  4. If theclosing procedure has not started yet, start it.

send

Run the steps described by thesend() algorithm with argument typestring object.

send

Run the steps described by thesend() algorithm with argument typeBlob object.

send

Run the steps described by thesend() algorithm with argument typeArrayBuffer object.

send

Run the steps described by thesend() algorithm with argument typeArrayBufferView object.

Thesend() method is overloaded to handle different data argument types. When any version of the method is called, the user agentMUSTrun the following steps:

  1. Letchannel be theRTCDataChannel object on which data is to be sent.

  2. Setchannel.[[IsTransferable]] tofalse.

  3. Ifchannel.[[ReadyState]] is not "open",throw anInvalidStateError.

  4. Execute the sub step that corresponds to the type of the methods argument:

    • string object:

      Letdata be a byte buffer that represents the result of encoding the method's argument as UTF-8.

    • Blob object:

      Letdata be the raw data represented by theBlob object.

      Note
      Although the actual retrieval ofdata from aBlob object can happen asynchronously, the user agent will make sure to queue the data on thechannel'sunderlying data transport in the same order as the send method is called. The byte size ofdata needs to be known synchronously.
    • ArrayBuffer object:

      Letdata be the data stored in the buffer described by theArrayBuffer object.

    • ArrayBufferView object:

      Letdata be the data stored in the section of the buffer described by theArrayBuffer object that theArrayBufferView object references.

    Note
    Any data argument type this method has not been overloaded with will result in aTypeError. This includesnull andundefined.
  5. If the byte size ofdata exceeds the value ofmaxMessageSize onchannel's associatedRTCSctpTransport,throw aTypeError.

  6. Queuedata for transmission onchannel'sunderlying data transport. If queuingdata is not possible because not enough buffer space is available,throw anOperationError.

    Note
    The actual transmission of data occursin parallel. If sending data leads to an SCTP-level error, the application will be notified asynchronously throughonerror.
  7. Increase the value of the[[BufferedAmount]] slot by the byte size ofdata.

WebIDLdictionaryRTCDataChannelInit {booleanordered = true;  [EnforceRange]unsigned shortmaxPacketLifeTime;  [EnforceRange]unsigned shortmaxRetransmits;USVStringprotocol = "";booleannegotiated = false;  [EnforceRange]unsigned shortid;};

DictionaryRTCDataChannelInit Members

ordered of typeboolean, defaulting totrue

If set to false, data is allowed to be delivered out of order. The default value of true, guarantees that data will be delivered in order.

maxPacketLifeTime of typeunsigned short

Limits the time (in milliseconds) during which the channel will transmit or retransmit data if not acknowledged. This value may be clamped if it exceeds the maximum value supported by the user agent.

maxRetransmits of typeunsigned short

Limits the number of times a channel will retransmit data if not successfully delivered. This value may be clamped if it exceeds the maximum value supported by the user agent.

protocol of typeUSVString, defaulting to""

Subprotocol name used for this channel.

negotiated of typeboolean, defaulting tofalse

The default value of false tells the user agent to announce the channel in-band and instruct the other peer to dispatch a correspondingRTCDataChannel object. If set to true, it is up to the application to negotiate the channel and create anRTCDataChannel object with the sameid at the other peer.

Note
If set to true, the application must also take care to not send a message until the other peer has created a data channel to receive it. Receiving a message on an SCTP stream with no associated data channel is undefined behavior, and it may be silently dropped. This will not be possible as long as both endpoints create their data channel before the first offer/answer exchange is complete.
id of typeunsigned short

Sets the channel ID whennegotiated is true. Ignored whennegotiated is false.

WebIDLenumRTCDataChannelState {"connecting","open","closing","closed"};
RTCDataChannelState Enumeration description
Enum valueDescription
connecting

The user agent is attempting to establish theunderlying data transport. This is the initial state of anRTCDataChannel object, whether created withcreateDataChannel, or dispatched as a part of anRTCDataChannelEvent.

open

Theunderlying data transport is established and communication is possible.

closing

Theprocedure to close down theunderlying data transport has started.

closed

Theunderlying data transport has beenclosed or could not be established.

6.3RTCDataChannelEvent

Thedatachannel event uses theRTCDataChannelEvent interface.

WebIDL[Exposed=Window]interfaceRTCDataChannelEvent :Event {constructor(DOMStringtype,RTCDataChannelEventIniteventInitDict);  readonly attributeRTCDataChannelchannel;};

Constructors

RTCDataChannelEvent.constructor()

Attributes

channel of typeRTCDataChannel, readonly

Thechannel attribute represents theRTCDataChannel object associated with the event.

WebIDLdictionaryRTCDataChannelEventInit :EventInit {  requiredRTCDataChannelchannel;};

DictionaryRTCDataChannelEventInit Members

channel of typeRTCDataChannel, required

TheRTCDataChannel object to be announced by the event.

6.4 Garbage Collection

AnRTCDataChannel objectMUST not be garbage collected if its

7. Peer-to-peer DTMF

This section describes an interface onRTCRtpSender to send DTMF (phone keypad) values across anRTCPeerConnection. Details of how DTMF is sent to the other peer are described in [RFC7874].

7.1 RTCRtpSender Interface Extensions

The Peer-to-peer DTMF API extends theRTCRtpSender interface as described below.

WebIDL          partial interfaceRTCRtpSender {  readonly attributeRTCDTMFSender?dtmf;};

Attributes

dtmf of typeRTCDTMFSender, readonly, nullable

On getting, thedtmf attribute returns the value of the[[Dtmf]] internal slot, which represents aRTCDTMFSender which can be used to send DTMF, ornull if unset. The[[Dtmf]] internal slot is set when the kind of anRTCRtpSender's[[SenderTrack]] is"audio".

7.2RTCDTMFSender

Tocreate an RTCDTMFSender, the user agentMUST run the following steps:

  1. Letdtmf be a newly createdRTCDTMFSender object.

  2. Letdtmf have a[[Duration]] internal slot.

  3. Letdtmf have a[[InterToneGap]] internal slot.

  4. Letdtmf have a[[ToneBuffer]] internal slot.

WebIDL[Exposed=Window]interfaceRTCDTMFSender :EventTarget {undefinedinsertDTMF(DOMStringtones, optionalunsigned longduration = 100, optionalunsigned longinterToneGap = 70);  attributeEventHandlerontonechange;  readonly attributebooleancanInsertDTMF;  readonly attributeDOMStringtoneBuffer;};

Attributes

ontonechange of typeEventHandler

The event type of this event handler istonechange.

canInsertDTMF of typeboolean, readonly

Whether theRTCDTMFSenderdtmfSender is capable of sending DTMF. On getting, the user agentMUST return the result of runningdetermine if DTMF can be sent fordtmfSender.

toneBuffer of typeDOMString, readonly

ThetoneBuffer attributeMUST return a list of the tones remaining to be played out. For the syntax, content, and interpretation of this list, seeinsertDTMF.

Methods

insertDTMF

AnRTCDTMFSender object'sinsertDTMF method is used to send DTMF tones.

The tones parameter is treated as a series of characters. The characters 0 through 9, A through D, #, and * generate the associated DTMF tones. The characters a to dMUST be normalized to uppercase on entry and are equivalent to A to D. As noted in [RTCWEB-AUDIO] Section 3, support for the characters 0 through 9, A through D, #, and * are required. The character ','MUST be supported, and indicates a delay of 2 seconds before processing the next character in the tones parameter. All other characters (and only those other characters)MUST be consideredunrecognized.

The duration parameter indicates the duration in ms to use for each character passed in the tones parameters. The duration cannot be more than 6000 ms or less than 40 ms. The default duration is 100 ms for each tone.

TheinterToneGap parameter indicates the gap between tones in ms. The user agent clamps it to at least 30 ms and at most 6000 ms. The default value is 70 ms.

The browserMAY increase theduration andinterToneGap times to cause the times that DTMF start and stop to align with the boundaries of RTP packets but itMUST not increase either of them by more than the duration of a single RTP audio packet.

When theinsertDTMF() method is invoked, the user agentMUST run the following steps:

  1. Letsender be theRTCRtpSender used to send DTMF.
  2. Lettransceiver be theRTCRtpTransceiver object associated withsender.

  3. Letdtmf be theRTCDTMFSender associated withsender.
  4. Ifdetermine if DTMF can be sent fordtmf returnsfalse,throw anInvalidStateError.
  5. Lettones be the method's first argument.
  6. Letduration be the method's second argument.
  7. LetinterToneGap be the method's third argument.
  8. If tones contains anyunrecognized characters,throw anInvalidCharacterError.
  9. Set the object's[[ToneBuffer]] slot totones.
  10. Setdtmf.[[Duration]] to the value ofduration.
  11. Setdtmf.[[InterToneGap]] to the value ofinterToneGap.
  12. If the value ofduration is less than 40 ms, setdtmf.[[Duration]] to 40 ms.
  13. If the value ofduration parameter is greater than 6000 ms, setdtmf.[[Duration]] to 6000 ms.
  14. If the value ofinterToneGap is less than 30 ms, setdtmf.[[InterToneGap]] to 30 ms.
  15. If the value ofinterToneGap is greater than 6000 ms, setdtmf.[[InterToneGap]] to 6000 ms.
  16. If [[ToneBuffer]] slot is an empty string, abort these steps.
  17. If a task to run theDTMF playout task steps is scheduled to be run, abort these steps; otherwise queue a task that runs the followingDTMF playout task steps:
    1. Candidate Correction 33:Determine if DTMF can be sent inside queued playout task (PR #2861)
    2. Iftransceiver.[[CurrentDirection]]Ifdetermine if DTMF can be sentis neither "sendrecv" nor "sendonly"fordtmf returnsfalse, abort these steps.
    3. If the[[ToneBuffer]] slot contains the empty string,fire an event namedtonechange using theRTCDTMFToneChangeEvent interface with thetone attribute set to an empty string at theRTCDTMFSender object and abort these steps.
    4. Remove the first character from the[[ToneBuffer]] slot and let that character betone.
    5. Iftone is"," delay sending tones for2000 ms on the associated RTP media stream, and queue a task to be executed in2000 ms from now that runs theDTMF playout task steps.
    6. Iftone is not"," start playout oftone for[[Duration]] ms on the associated RTP media stream, using the appropriate codec, then queue a task to be executed in[[Duration]] +[[InterToneGap]] ms from now that runs theDTMF playout task steps.
    7. Fire an event namedtonechange using theRTCDTMFToneChangeEvent interface with thetone attribute set totone at theRTCDTMFSender object.

SinceinsertDTMF replaces the tone buffer, in order to add to the DTMF tones being played, it is necessary to callinsertDTMF with a string containing both the remaining tones (stored in the[[ToneBuffer]] slot) and the new tones appended together. CallinginsertDTMF with an empty tones parameter can be used to cancel all tones queued to play after the currently playing tone.

7.3 canInsertDTMF algorithm

Todetermine if DTMF can be sent for anRTCDTMFSender instancedtmfSender, the user agentMUST run the following steps:

  1. Letsender be theRTCRtpSender associated withdtmfSender.
  2. Lettransceiver be theRTCRtpTransceiver associated withsender.
  3. Letconnection be theRTCPeerConnection associated withtransceiver.
  4. Ifconnection'sRTCPeerConnectionState is not "connected" returnfalse.
  5. Iftransceiver.[[Stopping]] istrue returnfalse.
  6. Ifsender.[[SenderTrack]] isnull returnfalse.
  7. Iftransceiver.[[CurrentDirection]] is neither "sendrecv" nor "sendonly" returnfalse.
  8. Ifsender.[[SendEncodings]][0].active isfalse returnfalse.
  9. If no codec with mimetype"audio/telephone-event" has been negotiated for sending with thissender, returnfalse.
  10. Otherwise, returntrue.

7.4RTCDTMFToneChangeEvent

Thetonechange event uses theRTCDTMFToneChangeEvent interface.

WebIDL[Exposed=Window]interfaceRTCDTMFToneChangeEvent :Event {constructor(DOMStringtype, optionalRTCDTMFToneChangeEventIniteventInitDict = {});  readonly attributeDOMStringtone;};

Constructors

RTCDTMFToneChangeEvent.constructor()

Attributes

tone of typeDOMString, readonly

Thetone attribute contains the character for the tone (including",") that has just begun playout (seeinsertDTMF ). If the value is the empty string, it indicates that the[[ToneBuffer]] slot is an empty string and that the previous tones have completed playback.

WebIDL          dictionaryRTCDTMFToneChangeEventInit :EventInit {DOMStringtone = "";};

DictionaryRTCDTMFToneChangeEventInit Members

tone of typeDOMString, defaulting to""

Thetone attribute contains the character for the tone (including",") that has just begun playout (seeinsertDTMF ). If the value is the empty string, it indicates that the[[ToneBuffer]] slot is an empty string and that the previous tones have completed playback.

8. Statistics Model

8.1 Introduction

The basic statistics model is that the browser maintains a set of statistics formonitored objects, in the form ofstats objects.

A group of related objects may be referenced by aselector. The selector may, for example, be aMediaStreamTrack. For a track to be a valid selector, itMUST be aMediaStreamTrack that is sent or received by theRTCPeerConnection object on which the stats request was issued. The calling Web application provides the selector to thegetStats() method and the browser emits (in the JavaScript) a set of statistics that are relevant to the selector, according to thestats selection algorithm. Note that that algorithm takes the sender or receiver of a selector.

The statistics returned instats objects are designed in such a way that repeated queries can be linked by theRTCStatsid dictionary member. Thus, a Web application can make measurements over a given time period by requesting measurements at the beginning and end of that period.

With a few exceptions,monitored objects, once created, exist for the duration of their associatedRTCPeerConnection. This ensures statistics from them are available in the result fromgetStats() even past the associated peer connection beingclosed.

Only a few monitored objects haveshorter lifetimes. Statistics from these objects are no longer available in subsequent getStats() results. The object descriptions in [WEBRTC-STATS] describe when these monitored objects are deleted.

8.2 RTCPeerConnection Interface Extensions

The Statistics API extends theRTCPeerConnection interface as described below.

WebIDL          partial interfaceRTCPeerConnection {Promise<RTCStatsReport>getStats(optionalMediaStreamTrack?selector = null);};

Methods

getStats

Gathers stats for the givenselector and reports the result asynchronously.

When thegetStats() method is invoked, the user agentMUST run the following steps:

  1. LetselectorArg be the method's first argument.

  2. Letconnection be theRTCPeerConnection object on which the method was invoked.

  3. IfselectorArg isnull, letselector benull.

  4. IfselectorArg is aMediaStreamTrack letselector be anRTCRtpSender orRTCRtpReceiver onconnection whichtrack attribute matchesselectorArg. If no such sender or receiver exists, or if more than one sender or receiver fit this criteria, return a promiserejected with a newlycreatedInvalidAccessError.

  5. Letp be a new promise.

  6. Run the following stepsin parallel:

    1. Gather the stats indicated byselector according to thestats selection algorithm.

    2. Queue a global task on thenetworking task source given the current realm'sglobal object asglobal toresolvep with the resultingRTCStatsReport object, containing the gathered stats.

  7. Returnp.

8.3RTCStatsReport Object

ThegetStats() method delivers a successful result in the form of anRTCStatsReport object. AnRTCStatsReport object is a map between strings that identify the inspected objects (id attribute inRTCStats instances), and their correspondingRTCStats-derived dictionaries.

AnRTCStatsReport may be composed of severalRTCStats-derived dictionaries, each reporting stats for one underlying object that the implementation thinks is relevant for theselector. One achieves the total for theselector by summing over all the stats of a certain type; for instance, if anRTCRtpSender uses multiple SSRCs to carry its track over the network, theRTCStatsReport may contain oneRTCStats-derived dictionary per SSRC (which can be distinguished by the value of thessrc stats attribute).

WebIDL[Exposed=Window]interfaceRTCStatsReport {  readonlymaplike<DOMString,object>;};

Use these to retrieve the various dictionaries descended fromRTCStats that this stats report is composed of. The set of supported property names [WEBIDL] is defined as the ids of all theRTCStats-derived dictionaries that have been generated for this stats report.

8.4RTCStats Dictionary

AnRTCStats dictionary represents thestats object constructed by inspecting a specificmonitored object. TheRTCStats dictionary is a base type that specifies as set of default attributes, such astimestamp andtype. Specific stats are added by extending theRTCStats dictionary.

Note that while stats names are standardized, any given implementation may be using experimental values or values not yet known to the Web application. Thus, applicationsMUST be prepared to deal with unknown stats.

Statistics need to be synchronized with each other in order to yield reasonable values in computation; for instance, ifbytesSent andpacketsSent are both reported, they both need to be reported over the same interval, so that "average packet size" can be computed as "bytes / packets" - if the intervals are different, this will yield errors. Thus implementationsMUST return synchronized values for all stats in anRTCStats-derived dictionary.

WebIDLdictionaryRTCStats {  requiredDOMHighResTimeStamptimestamp;  requiredRTCStatsTypetype;  requiredDOMStringid;};

DictionaryRTCStats Members

timestamp of typeDOMHighResTimeStamp
Candidate Correction 50:Use Performance.timeOrigin + Performance.now() for stats timestamps (PR #3005)

Thetimestamp, of typeTimestamps are expressed withDOMHighResTimeStamp,associated with this object. The time is relative to the UNIX epoch (Jan 1[HIGHRES-TIME],1970,and are defined asPerformance.timeOriginUTC)+Performance.now()at the time the information is collected.For statistics that came from a remote source (e.g., from received RTCP packets),timestamp represents the time at which the information arrived at the local endpoint. The remote timestamp can be found in an additional field in anRTCStats-derived dictionary, if applicable.

type of typeRTCStatsType

The type of this object.

Thetype attributeMUST be initialized to the name of the most specific type thisRTCStats dictionary represents.

id of typeDOMString

A uniqueid that is associated with the object that was inspected to produce thisRTCStats object. TwoRTCStats objects, extracted from two differentRTCStatsReport objects,MUST have the same id if they were produced by inspecting the same underlying object.

Stats idsMUST NOT be predictable by an application. This prevents applications from depending on a particular user agent's way of generating ids, since this prevents an application from getting stats objects by their id unless they have already read the id of that specific stats object.

User agents are free to pick any format for the id as long as it meets the requirements above.

Note

A user agent can turn a predictably generated string into an unpredictable string using a hash function, as long as it uses a salt that is unique to the peer connection. This allows an implementation to have predictable ids internally, which may make it easier to guarantee that stats objects have stable ids across getStats() calls.

The set of valid values forRTCStatsType, and the dictionaries derived from RTCStats that they indicate, are documented in [WEBRTC-STATS].

8.5 The stats selection algorithm

Thestats selection algorithm is as follows:

  1. Letresult be an emptyRTCStatsReport.
  2. Ifselector isnull, gather stats for the wholeconnection, add them toresult, returnresult, and abort these steps.
  3. Ifselector is anRTCRtpSender, gather stats for and add the following objects toresult:
  4. Ifselector is anRTCRtpReceiver, gather stats for and add the following objects toresult:
  5. Returnresult.

8.6 Mandatory To Implement Stats

The stats listed in [WEBRTC-STATS] are intended to cover a wide range of use cases. Not all of them have to be implemented by every WebRTC implementation.

An implementationMUST support generating statistics of the followingtypes when the corresponding objects exist on aRTCPeerConnection, with the fields that are listed when they are valid for that object in addition to the generic fields defined in theRTCStats dictionary:

RTCStatsType Dictionary Fields
"codec"RTCCodecStatspayloadType,mimeType,clockRate,channels,sdpFmtpLine
"inbound-rtp"RTCRtpStreamStatsssrc,kind,transportId,codecId
RTCReceivedRtpStreamStatspacketsReceived,packetsLost,jitter,
RTCInboundRtpStreamStatstrackIdentifier,remoteId,framesDecoded,framesDroppednackCount,framesReceived,bytesReceived,totalAudioEnergy,totalSamplesDurationpacketsDiscarded,
"outbound-rtp"RTCRtpStreamStatsssrc,kind,transportId,codecId
RTCSentRtpStreamStatspacketsSent,bytesSent
RTCOutboundRtpStreamStatsremoteId,framesEncoded,nackCount,framesSent
"remote-inbound-rtp"RTCRtpStreamStatsssrc,kind,transportId,codecId
RTCReceivedRtpStreamStatspacketsReceived,packetsLost,jitter
RTCRemoteInboundRtpStreamStatslocalId,roundTripTime
"remote-outbound-rtp"RTCRtpStreamStatsssrc,kind,transportId,codecId
RTCSentRtpStreamStatspacketsSent,bytesSent
RTCRemoteOutboundRtpStreamStatslocalId,remoteTimestamp
"media-source"RTCMediaSourceStatstrackIdentifier,kind
RTCAudioSourceStatstotalAudioEnergy,totalSamplesDuration (for audio tracks attached to senders)
RTCVideoSourceStatswidth,height,framesPerSecond (for video tracks attached to senders)
"peer-connection"RTCPeerConnectionStatsdataChannelsOpened,dataChannelsClosed
"data-channel"RTCDataChannelStatslabel ,protocol,dataChannelIdentifier,state,messagesSent,bytesSent,messagesReceived,bytesReceived
"transport"RTCTransportStatsbytesSent,bytesReceived,selectedCandidatePairId,localCertificateId,remoteCertificateId
"candidate-pair"RTCIceCandidatePairStatstransportId,localCandidateId,remoteCandidateId,state,nominated,bytesSent,bytesReceived,totalRoundTripTime,responsesReceived,currentRoundTripTime
"local-candidate"RTCIceCandidateStatsaddress,port,protocol,candidateType,url
"remote-candidate"
"certificate"RTCCertificateStatsfingerprint,fingerprintAlgorithm,base64Certificate,issuerCertificateId

An implementationMAY support generating any other statistic defined in [WEBRTC-STATS], andMAY generate statistics that are not documented.

8.7 GetStats Example

Consider the case where the user is experiencing bad sound and the application wants to determine if the cause of it is packet loss. The following example code might be used:

Example 8
asyncfunctiongatherStats(pc) {try {const [sender] = pc.getSenders();const baselineReport =await sender.getStats();awaitnewPromise(resolve =>setTimeout(resolve, aBit));// wait a bitconst currentReport =await sender.getStats();// compare the elements from the current report with the baselinefor (const nowof currentReport.values()) {if (now.type !='outbound-rtp')continue;// get the corresponding stats from the baseline reportconst base = baselineReport.get(now.id);if (!base)continue;const remoteNow = currentReport.get(now.remoteId);const remoteBase = baselineReport.get(base.remoteId);const packetsSent = now.packetsSent - base.packetsSent;const packetsReceived = remoteNow.packetsReceived -                              remoteBase.packetsReceived;const fractionLost = (packetsSent - packetsReceived) / packetsSent;if (fractionLost >0.3) {// if fractionLost is > 0.3, we have probably found the culprit      }    }  }catch (err) {console.error(err);  }}

9. Media Stream API Extensions for Network Use

9.1 Introduction

TheMediaStreamTrack interface, as defined in the [GETUSERMEDIA] specification, typically represents a stream of data of audio or video. One or moreMediaStreamTracks can be collected in aMediaStream (strictly speaking, aMediaStream as defined in [GETUSERMEDIA] may contain zero or moreMediaStreamTrack objects).

AMediaStreamTrack may be extended to represent a media flow that either comes from or is sent to a remote peer (and not just the local camera, for instance). The extensions required to enable this capability on theMediaStreamTrack object will be described in this section. How the media is transmitted to the peer is described in [RFC8834], [RFC7874], and [RFC8835].

AMediaStreamTrack sent to another peer will appear as one and only oneMediaStreamTrack to the recipient. A peer is defined as a user agent that supports this specification. In addition, the sending side application can indicate whatMediaStream object(s) theMediaStreamTrack is a member of. The correspondingMediaStream object(s) on the receiver side will be created (if not already present) and populated accordingly.

As also described earlier in this document, the objectsRTCRtpSender andRTCRtpReceiver can be used by the application to get more fine grained control over the transmission and reception ofMediaStreamTracks.

Channels are the smallest unit considered in the Media Capture and Streams specification. Channels are intended to be encoded together for transmission as, for instance, an RTP payload type. All of the channels that a codec needs to encode jointlyMUST be in the sameMediaStreamTrack and the codecsSHOULD be able to encode, or discard, all the channels in the track.

The concepts of an input and output to a givenMediaStreamTrack apply in the case ofMediaStreamTrack objects transmitted over the network as well. AMediaStreamTrack created by anRTCPeerConnection object (as described previously in this document) will take as input the data received from a remote peer. Similarly, aMediaStreamTrack from a local source, for instance a camera via [GETUSERMEDIA], will have an output that represents what is transmitted to a remote peer if the object is used with anRTCPeerConnection object.

The concept of duplicatingMediaStream andMediaStreamTrack objects as described in [GETUSERMEDIA] is also applicable here. This feature can be used, for instance, in a video-conferencing scenario to display the local video from the user's camera and microphone in a local monitor, while only transmitting the audio to the remote peer (e.g. in response to the user using a "video mute" feature). Combining differentMediaStreamTrack objects into newMediaStream objects is useful in certain situations.

Note

In this document, we only specify aspects of the following objects that are relevant when used along with anRTCPeerConnection. Please refer to the original definitions of the objects in the [GETUSERMEDIA] document for general information on usingMediaStream andMediaStreamTrack.

9.2 MediaStream

9.2.1 id

Theid attribute specified inMediaStream returns an id that is unique to this stream, so that streams can be recognized at the remote end of theRTCPeerConnection API.

When aMediaStream is created to represent a stream obtained from a remote peer, theid attribute is initialized from information provided by the remote source.

Note

Theid of aMediaStream object is unique to the source of the stream, but that does not mean it is not possible to end up with duplicates. For example, the tracks of a locally generated stream could be sent from one user agent to a remote peer usingRTCPeerConnection and then sent back to the original user agent in the same manner, in which case the original user agent will have multiple streams with the same id (the locally-generated one and the one received from the remote peer).

9.3 MediaStreamTrack

AMediaStreamTrack object's reference to itsMediaStream in the non-local media source case (an RTP source, as is the case for eachMediaStreamTrack associated with anRTCRtpReceiver) is always strong.

Whenever anRTCRtpReceiver receives data on an RTP source whose correspondingMediaStreamTrack is muted, but not ended, and the[[Receptive]] slot of theRTCRtpTransceiver object theRTCRtpReceiver is a member of istrue, itMUST queue a task toset the muted state of the correspondingMediaStreamTrack tofalse.

When one of the SSRCs for RTP source media streams received by anRTCRtpReceiver is removed either due to reception of a BYE or via timeout, itMUST queue a task toset the muted state of the correspondingMediaStreamTrack totrue. Note thatsetRemoteDescription can also lead tothe setting of the muted state of thetrack to the valuetrue.

The proceduresadd a track,remove a track andset a track's muted state are specified in [GETUSERMEDIA].

When aMediaStreamTrack track produced by anRTCRtpReceiverreceiver hasended [GETUSERMEDIA] (such as via a call toreceiver.track.stop), the user agentMAY choose to free resources allocated for the incoming stream, by for instance turning off the decoder ofreceiver.

9.3.1 MediaTrackSupportedConstraints, MediaTrackCapabilities, MediaTrackConstraints and MediaTrackSettings

The concept of constraints and constrainable properties, includingMediaTrackConstraints (MediaStreamTrack.getConstraints(),MediaStreamTrack.applyConstraints()), andMediaTrackSettings (MediaStreamTrack.getSettings()) are outlined in [GETUSERMEDIA]. However, the constrainable properties of tracks sourced from a peer connection are different than those sourced bygetUserMedia(); the constraints and settings applicable toMediaStreamTracks sourced from aremote source are defined here. The settings of a remote track represent the latest frame received.

MediaStreamTrack.getCapabilities()MUST always return the empty set andMediaStreamTrack.applyConstraints()MUST always reject withOverconstrainedError on remote tracks for constraints defined here.

The following constrainable properties are defined to apply to videoMediaStreamTracks sourced from aremote source:

Property Name Values Notes
widthConstrainULong As a setting, this is the width, in pixels, of the latest frame received.
heightConstrainULong As a setting, this is the height, in pixels, of the latest frame received.
frameRateConstrainDouble As a setting, this is an estimate of the frame rate based on recently received frames.
aspectRatioConstrainDouble As a setting, this is the aspect ratio of the latest frame; this is the width in pixels divided by height in pixels as a double rounded to the tenth decimal place.

This document does not define any constrainable properties to apply to audioMediaStreamTracks sourced from aremote source.

10. Examples and Call Flows

This section is non-normative.

10.1 Simple Peer-to-peer Example

When two peers decide they are going to set up a connection to each other, they both go through these steps. The STUN/TURN server configuration describes a server they can use to get things like their public IP address or to set up NAT traversal. They also have to send data for the signaling channel to each other using the same out-of-band mechanism they used to establish that they were going to communicate in the first place.

Example 9
const signaling =newSignalingChannel();// handles JSON.stringify/parseconst constraints = {audio:true,video:true};const configuration = {iceServers: [{urls:'stun:stun.example.org'}]};const pc =newRTCPeerConnection(configuration);// send any ice candidates to the other peerpc.onicecandidate =({candidate}) => signaling.send({candidate});// let the "negotiationneeded" event trigger offer generationpc.onnegotiationneeded =async () => {try {await pc.setLocalDescription();// send the offer to the other peer    signaling.send({description: pc.localDescription});  }catch (err) {console.error(err);  }};pc.ontrack =({track, streams}) => {// once media for a remote track arrives, show it in the remote video element  track.onunmute =() => {// don't set srcObject again if it is already set.if (remoteView.srcObject)return;    remoteView.srcObject = streams[0];  };};// call start() to initiatefunctionstart() {addCameraMic();}// add camera and microphone to connectionasyncfunctionaddCameraMic() {try {// get a local stream, show it in a self-view and add it to be sentconst stream =await navigator.mediaDevices.getUserMedia(constraints);for (const trackof stream.getTracks()) {      pc.addTrack(track, stream);    }    selfView.srcObject = stream;  }catch (err) {console.error(err);  }}signaling.onmessage =async ({data: {description, candidate}}) => {try {if (description) {await pc.setRemoteDescription(description);// if we got an offer, we need to reply with an answerif (description.type =='offer') {if (!selfView.srcObject) {// blocks negotiation on permission (not recommended in production code)awaitaddCameraMic();        }await pc.setLocalDescription();        signaling.send({description: pc.localDescription});      }    }elseif (candidate) {await pc.addIceCandidate(candidate);    }  }catch (err) {console.error(err);  }};

10.2 Advanced Peer-to-peer Example with Warm-up

When two peers decide they are going to set up a connection to each other and want to have the ICE, DTLS, and media connections "warmed up" such that they are ready to send and receive media immediately, they both go through these steps.

Example 10
const signaling =newSignalingChannel();// handles JSON.stringify/parseconst constraints = {audio:true,video:true};const configuration = {iceServers: [{urls:'stun:stun.example.org'}]};let pc;let audio;let video;let started =false;// Call warmup() before media is ready, to warm-up ICE, DTLS, and media.asyncfunctionwarmup(isAnswerer) {  pc =newRTCPeerConnection(configuration);if (!isAnswerer) {    audio = pc.addTransceiver('audio');    video = pc.addTransceiver('video');  }// send any ice candidates to the other peer  pc.onicecandidate =({candidate}) => signaling.send({candidate});// let the "negotiationneeded" event trigger offer generation  pc.onnegotiationneeded =async () => {try {await pc.setLocalDescription();// send the offer to the other peer      signaling.send({description: pc.localDescription});    }catch (err) {console.error(err);    }  };  pc.ontrack =async ({track, transceiver}) => {try {// once media for the remote track arrives, show it in the video element      event.track.onunmute =() => {// don't set srcObject again if it is already set.if (!remoteView.srcObject) {          remoteView.srcObject =newMediaStream();        }        remoteView.srcObject.addTrack(track);      }if (isAnswerer) {if (track.kind =='audio') {          audio = transceiver;        }elseif (track.kind =='video') {          video = transceiver;        }if (started)awaitaddCameraMicWarmedUp();      }    }catch (err) {console.error(err);    }  };try {// get a local stream, show it in a self-view and add it to be sent    selfView.srcObject =await navigator.mediaDevices.getUserMedia(constraints);if (started)awaitaddCameraMicWarmedUp();  }catch (err) {console.error(err);  }}// call start() after warmup() to begin transmitting media from both endsfunctionstart() {  signaling.send({start:true});  signaling.onmessage({data: {start:true}});}// add camera and microphone to already warmed-up connectionasyncfunctionaddCameraMicWarmedUp() {const stream = selfView.srcObject;if (audio && video && stream) {awaitPromise.all([      audio.sender.replaceTrack(stream.getAudioTracks()[0]),      video.sender.replaceTrack(stream.getVideoTracks()[0]),    ]);  }}signaling.onmessage =async ({data: {start, description, candidate}}) => {if (!pc)warmup(true);try {if (start) {      started =true;awaitaddCameraMicWarmedUp();    }elseif (description) {await pc.setRemoteDescription(description);// if we got an offer, we need to reply with an answerif (description.type =='offer') {await pc.setLocalDescription();        signaling.send({description: pc.localDescription});      }    }else {await pc.addIceCandidate(candidate);    }  }catch (err) {console.error(err);  }};

10.3 Simulcast Example

A client wants to send multiple RTP encodings (simulcast) to a server.

Example 11
const signaling =newSignalingChannel();// handles JSON.stringify/parseconst constraints = {audio:true,video:true};const configuration = {'iceServers': [{'urls':'stun:stun.example.org'}]};let pc;// call start() to initiateasyncfunctionstart() {  pc =newRTCPeerConnection(configuration);// let the "negotiationneeded" event trigger offer generation  pc.onnegotiationneeded =async () => {try {await pc.setLocalDescription();// send the offer to the other peer      signaling.send({description: pc.localDescription});    }catch (err) {console.error(err);    }  };try {// get a local stream, show it in a self-view and add it to be sentconst stream =await navigator.mediaDevices.getUserMedia(constraints);    selfView.srcObject = stream;    pc.addTransceiver(stream.getAudioTracks()[0], {direction:'sendonly'});    pc.addTransceiver(stream.getVideoTracks()[0], {direction:'sendonly',sendEncodings: [        {rid:'q',scaleResolutionDownBy:4.0}        {rid:'h',scaleResolutionDownBy:2.0},        {rid:'f'},      ]    });  }catch (err) {console.error(err);  }}signaling.onmessage =async ({data: {description, candidate}}) => {try {if (description) {await pc.setRemoteDescription(description);// if we got an offer, we need to reply with an answerif (description.type =='offer') {await pc.setLocalDescription();        signaling.send({description: pc.localDescription});      }    }elseif (candidate) {await pc.addIceCandidate(candidate);    }  }catch (err) {console.error(err);  }};

10.4 Peer-to-peer Data Example

This example shows how to create anRTCDataChannel object and perform the offer/answer exchange required to connect the channel to the other peer. TheRTCDataChannel is used in the context of a simple chat application using aninput field for user input.

Example 12
const signaling =newSignalingChannel();// handles JSON.stringify/parseconst configuration = {iceServers: [{urls:'stun:stun.example.org'}]};let pc, channel;// call start() to initiatefunctionstart() {  pc =newRTCPeerConnection(configuration);// send any ice candidates to the other peer  pc.onicecandidate =({candidate}) => signaling.send({candidate});// let the "negotiationneeded" event trigger offer generation  pc.onnegotiationneeded =async () => {try {await pc.setLocalDescription();// send the offer to the other peer      signaling.send({description: pc.localDescription});    }catch (err) {console.error(err);    }  };// create data channel and setup chat using "negotiated" pattern  channel = pc.createDataChannel('chat', {negotiated:true,id:0});  channel.onopen =() => input.disabled =false;  channel.onmessage =({data}) =>showChatMessage(data);  input.onkeydown =({key}) => {if (key !='Enter')return;    channel.send(input.value);  }}signaling.onmessage =async ({data: {description, candidate}}) => {if (!pc)start();try {if (description) {await pc.setRemoteDescription(description);// if we got an offer, we need to reply with an answerif (description.type =='offer') {await pc.setLocalDescription();        signaling.send({description: pc.localDescription});      }    }elseif (candidate) {await pc.addIceCandidate(candidate);    }  }catch (err) {console.error(err);  }};

10.5 Call Flow Browser to Browser

This shows an example of one possible call flow between two browsers. This does not show the procedure to get access to local media or every callback that gets fired but instead tries to reduce it down to only show the key events and messages.

A message sequence chart detailing a call flow between two browsers

10.6 DTMF Example

Examples assume thatsender is anRTCRtpSender.

Sending the DTMF signal "1234" with 500 ms duration per tone:

Example 13
if (sender.dtmf.canInsertDTMF) {const duration =500;  sender.dtmf.insertDTMF('1234', duration);}else {console.log('DTMF function not available');}

Send the DTMF signal "123" and abort after sending "2".

Example 14
asyncfunctionsendDTMF() {if (sender.dtmf.canInsertDTMF) {    sender.dtmf.insertDTMF('123');awaitnewPromise(r => sender.dtmf.ontonechange =e => e.tone =='2' &&r());// empty the buffer to not play any tone after "2"    sender.dtmf.insertDTMF('');  }else {console.log('DTMF function not available');  }}

Send the DTMF signal "1234", and light up the active key usinglightKey(key) while the tone is playing (assuming thatlightKey("") will darken all the keys):

Example 15
constwait = ms =>newPromise(resolve =>setTimeout(resolve, ms));if (sender.dtmf.canInsertDTMF) {const duration =500;// ms  sender.dtmf.insertDTMF(sender.dtmf.toneBuffer +'1234', duration);  sender.dtmf.ontonechange =async ({tone}) => {if (!tone)return;lightKey(tone);// light up the key when playout startsawaitwait(duration);lightKey('');// turn off the light after tone duration  };}else {console.log('DTMF function not available');}

It is always safe to append to the tone buffer. This example appends before any tone playout has started as well as during playout.

Example 16
if (sender.dtmf.canInsertDTMF) {  sender.dtmf.insertDTMF('123');// append more tones to the tone buffer before playout has begun  sender.dtmf.insertDTMF(sender.dtmf.toneBuffer +'456');  sender.dtmf.ontonechange =({tone}) => {// append more tones when playout has begunif (tone !='1')return;    sender.dtmf.insertDTMF(sender.dtmf.toneBuffer +'789');  };}else {console.log('DTMF function not available');}

Send a 1-second "1" tone followed by a 2-second "2" tone:

Example 17
if (sender.dtmf.canInsertDTMF) {  sender.dtmf.ontonechange =({tone}) => {if (tone =='1') {      sender.dtmf.insertDTMF(sender.dtmf.toneBuffer +'2',2000);    }  };  sender.dtmf.insertDTMF(sender.dtmf.toneBuffer +'1',1000);}else {console.log('DTMF function not available');}

10.7 Perfect Negotiation Example

Perfect negotiation is a recommended pattern to manage negotiation transparently, abstracting this asymmetric task away from the rest of an application. This pattern has advantages over one side always being the offerer, as it lets applications operate on both peer connection objects simultaneously without risk of glare (an offer coming in outside of "stable" state). The rest of the application may use any and all modification methods and attributes, without worrying about signaling state races.

It designates different roles to the two peers, with behavior to resolve signaling collisions between them:

  1. The polite peer uses rollback to avoid collision with an incoming offer.

  2. The impolite peer ignores an incoming offer when this would collide with its own.

Together, they manage signaling for the rest of the application in a manner that doesn't deadlock. The example assumes apolite boolean variable indicating the designated role:

Example 18
const signaling =newSignalingChannel();// handles JSON.stringify/parseconst constraints = {audio:true,video:true};const configuration = {iceServers: [{urls:'stun:stun.example.org'}]};const pc =newRTCPeerConnection(configuration);// call start() anytime on either end to add camera and microphone to connectionasyncfunctionstart() {try {const stream =await navigator.mediaDevices.getUserMedia(constraints);for (const trackof stream.getTracks()) {      pc.addTrack(track, stream);    }    selfView.srcObject = stream;  }catch (err) {console.error(err);  }}pc.ontrack =({track, streams}) => {// once media for a remote track arrives, show it in the remote video element  track.onunmute =() => {// don't set srcObject again if it is already set.if (remoteView.srcObject)return;    remoteView.srcObject = streams[0];  };};// - The perfect negotiation logic, separated from the rest of the application ---// keep track of some negotiation state to prevent races and errorslet makingOffer =false;let ignoreOffer =false;let isSettingRemoteAnswerPending =false;// send any ice candidates to the other peerpc.onicecandidate =({candidate}) => signaling.send({candidate});// let the "negotiationneeded" event trigger offer generationpc.onnegotiationneeded =async () => {try {    makingOffer =true;await pc.setLocalDescription();    signaling.send({description: pc.localDescription});  }catch (err) {console.error(err);  }finally {    makingOffer =false;  }};signaling.onmessage =async ({data: {description, candidate}}) => {try {if (description) {// An offer may come in while we are busy processing SRD(answer).// In this case, we will be in "stable" by the time the offer is processed// so it is safe to chain it on our Operations Chain now.const readyForOffer =          !makingOffer &&          (pc.signalingState =="stable" || isSettingRemoteAnswerPending);const offerCollision = description.type =="offer" && !readyForOffer;      ignoreOffer = !polite && offerCollision;if (ignoreOffer) {return;      }      isSettingRemoteAnswerPending = description.type =="answer";await pc.setRemoteDescription(description);// SRD rolls back as needed      isSettingRemoteAnswerPending =false;if (description.type =="offer") {await pc.setLocalDescription();        signaling.send({description: pc.localDescription});      }    }elseif (candidate) {try {await pc.addIceCandidate(candidate);      }catch (err) {if (!ignoreOffer)throw err;// Suppress ignored offer's candidates      }    }  }catch (err) {console.error(err);  }}

Note that this is timing sensitive, and deliberately uses versions ofsetLocalDescription (without arguments) andsetRemoteDescription (with implicit rollback) to avoid races with other signaling messages being serviced.

TheignoreOffer variable is needed, because theRTCPeerConnection object on the impolite side is never told about ignored offers. We must therefore suppress errors from incoming candidates belonging to such offers.

11. Error Handling

Some operations throw or fireRTCError. This is an extension ofDOMException that carries additional WebRTC-specific information.

11.1RTCError Interface

WebIDL[Exposed=Window]interfaceRTCError :DOMException {constructor(RTCErrorInitinit, optionalDOMStringmessage = "");  readonly attributeRTCErrorDetailTypeerrorDetail;  readonly attributelong?sdpLineNumber;  readonly attributelong?sctpCauseCode;  readonly attributeunsigned long?receivedAlert;  readonly attributeunsigned long?sentAlert;};

11.1.1 Constructors

constructor()

Run the following steps:

  1. Letinit be the constructor's first argument.

  2. Letmessage be the constructor's second argument.

  3. Lete be a newRTCError object.

  4. Invoke theDOMException constructor ofe with themessage argument set tomessage and thename argument set to"OperationError".

    Note

    This name does not have a mapping to a legacy code soe.code will return 0.

  5. Set allRTCError attributes ofe to the value of the corresponding attribute ininit if it is present, otherwise set it tonull.

  6. Returne.

11.1.2 Attributes

errorDetail of typeRTCErrorDetailType, readonly

The WebRTC-specific error code for the type of error that occurred.

sdpLineNumber of typelong, readonly, nullable

IferrorDetail is "sdp-syntax-error" this is the line number where the error was detected (the first line has line number 1).

sctpCauseCode of typelong, readonly, nullable

IferrorDetail is "sctp-failure" this is the SCTP cause code of the failed SCTP negotiation.

receivedAlert of typeunsigned long, readonly, nullable

IferrorDetail is "dtls-failure" and a fatal DTLS alert was received, this is the value of the DTLS alert received.

sentAlert of typeunsigned long, readonly, nullable

IferrorDetail is "dtls-failure" and a fatal DTLS alert was sent, this is the value of the DTLS alert sent.

(Feature at Risk) Issue 1

All attributes defined inRTCError are marked at risk due to lack of implementation (errorDetail,sdpLineNumber,sctpCauseCode,receivedAlert andsentAlert). This does not include attributes inherited fromDOMException.

11.1.3RTCErrorInit Dictionary

WebIDLdictionaryRTCErrorInit {  requiredRTCErrorDetailTypeerrorDetail;longsdpLineNumber;longsctpCauseCode;unsigned longreceivedAlert;unsigned longsentAlert;};

TheerrorDetail,sdpLineNumber,sctpCauseCode,receivedAlert andsentAlert members ofRTCErrorInit have the same definitions as the attributes of the same name ofRTCError.

11.2RTCErrorDetailType Enum

WebIDLenumRTCErrorDetailType {"data-channel-failure","dtls-failure","fingerprint-failure","sctp-failure","sdp-syntax-error","hardware-encoder-not-available","hardware-encoder-error"};
RTCErrorDetailType Enumeration description
Enum valueDescription
data-channel-failure The data channel has failed.
dtls-failure The DTLS negotiation has failed or the connection has been terminated with a fatal error. Themessage contains information relating to the nature of error. If a fatal DTLS alert was received, thereceivedAlert attribute is set to the value of the DTLS alert received. If a fatal DTLS alert was sent, thesentAlert attribute is set to the value of the DTLS alert sent.
fingerprint-failure TheRTCDtlsTransport's remote certificate did not match any of the fingerprints provided in the SDP. If the remote peer cannot match the local certificate against the provided fingerprints, this error is not generated. Instead a "bad_certificate" (42) DTLS alert might be received from the remote peer, resulting in a "dtls-failure".
sctp-failure The SCTP negotiation has failed or the connection has been terminated with a fatal error. ThesctpCauseCode attribute is set to the SCTP cause code.
sdp-syntax-error The SDP syntax is not valid. ThesdpLineNumber attribute is set to the line number in the SDP where the syntax error was detected.
hardware-encoder-not-available The hardware encoder resources required for the requested operation are not available.
hardware-encoder-error The hardware encoder does not support the provided parameters.

11.3RTCErrorEvent Interface

TheRTCErrorEvent interface is defined for cases when anRTCError is raised as an event:

WebIDL[Exposed=Window]interfaceRTCErrorEvent :Event {constructor(DOMStringtype,RTCErrorEventIniteventInitDict);  [SameObject] readonly attributeRTCErrorerror;};

11.3.1 Constructors

constructor()

Constructs a newRTCErrorEvent.

11.3.2 Attributes

error of typeRTCError, readonly

TheRTCError describing the error that triggered the event.

11.4RTCErrorEventInit Dictionary

WebIDL          dictionaryRTCErrorEventInit :EventInit {  requiredRTCErrorerror;};

11.4.1 Dictionary RTCErrorEventInit Members

error of typeRTCError

TheRTCError describing the error associated with the event (if any).

12. Event summary

This section is non-normative.

The following events fire onRTCDataChannel objects:

Event name Interface Fired when...
openEvent TheRTCDataChannel object'sunderlying data transport has been established (or re-established).
messageMessageEvent [html] A message was successfully received.
bufferedamountlowEvent TheRTCDataChannel object'sbufferedAmount decreases from above itsbufferedAmountLowThreshold to less than or equal to itsbufferedAmountLowThreshold.
errorRTCErrorEvent An error occurred on the data channel.
closingEvent TheRTCDataChannel object transitions to the "closing" state
closeEvent TheRTCDataChannel object'sunderlying data transport has been closed.

The following events fire onRTCPeerConnection objects:

Event name Interface Fired when...
trackRTCTrackEvent New incoming media has been negotiated for a specificRTCRtpReceiver, and that receiver'strack has been added to any associated remoteMediaStreams.
negotiationneededEvent The browser wishes to inform the application that session negotiation needs to be done (i.e. a createOffer call followed by setLocalDescription).
signalingstatechangeEvent The connection's[[SignalingState]] has changed. This state change is the result of eithersetLocalDescription orsetRemoteDescription being invoked.
iceconnectionstatechangeEvent TheRTCPeerConnection's[[IceConnectionState]] has changed.
icegatheringstatechangeEvent TheRTCPeerConnection's[[IceGatheringState]] has changed.
icecandidateRTCPeerConnectionIceEvent A newRTCIceCandidate is made available to the script.
connectionstatechangeEvent TheRTCPeerConnection.connectionState has changed.
icecandidateerrorRTCPeerConnectionIceErrorEvent A failure occured when gathering ICE candidates.
datachannelRTCDataChannelEvent A newRTCDataChannel is dispatched to the script in response to the other peer creating a channel.

The following events fire onRTCDTMFSender objects:

Event name Interface Fired when...
tonechangeRTCDTMFToneChangeEvent TheRTCDTMFSender object has either just begun playout of a tone (returned as thetone attribute) or just ended the playout of tones in thetoneBuffer (returned as an empty value in thetone attribute).

The following events fire onRTCIceTransport objects:

Event name Interface Fired when...
statechangeEvent TheRTCIceTransport state changes.
gatheringstatechangeEvent TheRTCIceTransport gathering state changes.
selectedcandidatepairchangeEvent TheRTCIceTransport's selected candidate pair changes.

The following events fire onRTCDtlsTransport objects:

Event name Interface Fired when...
statechangeEvent TheRTCDtlsTransport state changes.
errorRTCErrorEvent An error occurred on theRTCDtlsTransport (either "dtls-failure" or "fingerprint-failure").

The following events fire onRTCSctpTransport objects:

Event name Interface Fired when...
statechangeEvent TheRTCSctpTransport state changes.

13. Privacy and Security Considerations

This section is non-normative.

This section is non-normative; it specifies no new behaviour, but instead summarizes information already present in other parts of the specification. The overall security considerations of the general set of APIs and protocols used in WebRTC are described in [RFC8827].

13.1 Impact on same origin policy

This document extends the Web platform with the ability to set up real-time, direct communication between browsers and other devices, including other browsers.

This means that data and media can be shared between applications running in different browsers, or between an application running in the same browser and something that is not a browser, something that is an extension to the usual barriers in the Web model against sending data between entities with different origins.

The WebRTC specification provides no user prompts or chrome indicators for communication; it assumes that once the Web page has been allowed to access media, it is free to share that media with other entities as it chooses. Peer-to-peer exchanges of data view WebRTC datachannels can thus occur without any user explicit consent or involvement, similarly as a server-mediated exchange (e.g. via Web Sockets) could occur without user involvement.

13.2 Revealing IP addresses

Even without WebRTC, the Web server providing a Web application will know the public IP address to which the application is delivered. Setting up communications exposes additional information about the browser’s network context to the web application, and may include the set of (possibly private) IP addresses available to the browser for WebRTC use. Some of this information has to be passed to the corresponding party to enable the establishment of a communication session.

Revealing IP addresses can leak location and means of connection; this can be sensitive. Depending on the network environment, it can also increase the fingerprinting surface and create persistent cross-origin state that cannot easily be cleared by the user.

A connection will always reveal the IP addresses proposed for communication to the corresponding party. The application can limit this exposure by choosing not to use certain addresses using the settings exposed by theRTCIceTransportPolicy dictionary, and by using relays (for instance TURN servers) rather than direct connections between participants. One will normally assume that the IP address of TURN servers is not sensitive information. These choices can for instance be made by the application based on whether the user has indicated consent to start a media connection with the other party.

Mitigating the exposure of IP addresses to the application itself requires limiting the IP addresses that can be used, which will impact the ability to communicate on the most direct path between endpoints. Browsers are encouraged to provide appropriate controls for deciding which IP addresses are made available to applications, based on the security posture desired by the user. The choice of which addresses to expose is controlled by local policy (see [RFC8828] for details).

13.3 Impact on local network

Since the browser is an active platform executing in a trusted network environment (inside the firewall), it is important to limit the damage that the browser can do to other elements on the local network, and it is important to protect data from interception, manipulation and modification by untrusted participants.

Mitigations include:

These measures are specified in the relevant IETF documents.

13.4 Confidentiality of Communications

The fact that communication is taking place cannot be hidden from adversaries that can observe the network, so this has to be regarded as public information.

Communication certificates may be opaquely shared usingpostMessage(message,options) in anticipation of future needs. User agents are strongly encouraged to isolate the private keying material these objects hold a handle to, from the processes that have access to theRTCCertificate objects, to reduce memory attack surface.

13.5 Persistent information exposed by WebRTC

As described above, the list of IP addresses exposed by the WebRTC API can be used as a persistent cross-origin state.

Beyond IP addresses, the WebRTC API exposes information about the underlying media system via theRTCRtpSender.getCapabilities andRTCRtpReceiver.getCapabilities methods, including detailed and ordered information about the codecs that the system is able to produce and consume. A subset of that information is likely to be represented in the SDP session descriptions generated, exposed and transmitted duringsession negotiation. That information is in most cases persistent across time and origins, and increases the fingerprint surface of a given device.

When establishing DTLS connections, the WebRTC API can generate certificates that can be persisted by the application (e.g. in IndexedDB). These certificates are not shared across origins, and get cleared when persistent storage is cleared for the origin.

13.6 Setting SDP from remote endpoints

setRemoteDescription guards against malformed and invalid SDP by throwing exceptions, but makes no attempt to guard against SDP that might be unexpected by the application. Setting the remote description can cause significant resources to be allocated (including image buffers and network ports), media to start flowing (which may have privacy and bandwidth implications) among other things. An application that does not guard against malicious SDP could be at risk of resource deprivation, unintentionally allowing incoming media or at risk of not having certain events fire likeontrack if the other endpoint does not negotiate sending. Applications need to be on guard against malevolent SDP.

14. Accessibility Considerations

This section is non-normative.

The WebRTC 1.0 specification exposes an API to control protocols (defined within the IETF) necessary to establish real-time audio, video and data exchange.

The Telecommunications Device for the Deaf (TDD/TTY) enables individuals who are hearing or speech impaired (among others) to communicate over telephone lines. Real-Time Text, defined in [RFC4103], utilizes T.140 encapsulated in RTP to enable the transition from TDD/TTY devices to IP-based communications, including emergency communication with Public Safety Access Points (PSAP).

Since Real-Time Text requires the ability to send and receive data in near real time, it can be best supported via the WebRTC 1.0 data channel API. As defined by the IETF, the data channel protocol utilizes the SCTP/DTLS/UDP protocol stack, which supports both reliable and unreliable data channels. The IETF chose to standardize SCTP/DTLS/UDP over proposals for an RTP data channel which relied on SRTP key management and were focused on unreliable communications.

Since the IETF chose a different approach than the RTP data channel as part of the WebRTC suite of protocols, as of the time of this publication there is no standardized way for the WebRTC APIs to directly support Real-Time Text as defined at IETF and implemented in U.S. (FCC) regulations. The WebRTC working Group will evaluate whether the developing IETF protocols in this space warrant direct exposure in the browser APIs and is looking for input from the relevant user communities on this potential gap.

Within theIETF MMUSIC Working Group, work is ongoing to enable Real-time text to be sent over the WebRTC data channel, allowing gateways to be deployed to translate between the SCTP data channel protocol and RFC 4103 Real-Time Text. This work, once completed, is expected to enable a unified and interoperable approach for integrating real-time text in WebRTC user-agents (including browsers) - through a gateway or otherwise.

At the time of this publication, gateways that enable effective RTT support in WebRTC clients can be developed e.g. through a custom WebRTC data channel. This is deemed sufficient until such time as future standardized gateways are enabled via IETF protocols such as the SCTP data channel protocol and RFC 4103 Real-Time Text. This will need to be defined at IETF in conjunction with related work atW3C groups to effectively and consistently standardise RTT support internationally.

A. Candidate Amendments

Since its publication as aW3C Recommendation in January 2021, the followingcandidate amendments have been integrated in this document.

B. Acknowledgements

The editors wish to thank the Working Group chairs and Team Contact, Harald Alvestrand, Stefan Håkansson, Erik Lagerway and Dominique Hazaël-Massieux, for their support. Substantial text in this specification was provided by many people including Martin Thomson, Harald Alvestrand, Justin Uberti, Eric Rescorla, Peter Thatcher, Jan-Ivar Bruaroey and Peter Saint-Andre. Dan Burnett would like to acknowledge the significant support received from Voxeo and Aspect during the development of this specification.

TheRTCRtpSender andRTCRtpReceiver objects were initially described in theW3C ORTC CG, and have been adapted for use in this specification.

C.References

Candidate Correction 46:Replace RFC8829 reference with RFC9429 (PR #2966)

B.1Normative references

C.1Normative references

[DOM]
DOM Standard. Anne van Kesteren. WHATWG. Living Standard. URL:https://dom.spec.whatwg.org/
[ECMASCRIPT-6.0]
ECMA-262 6th Edition, The ECMAScript 2015 Language Specification. Allen Wirfs-Brock. Ecma International. June 2015. Standard. URL:http://www.ecma-international.org/ecma-262/6.0/index.html
[Fetch]
Fetch Standard. Anne van Kesteren. WHATWG. Living Standard. URL:https://fetch.spec.whatwg.org/
[FILEAPI]
File API. Marijn Kruisselbrink; Arun Ranganathan. W3C.11 September 20194 December 2024. W3C Working Draft. URL:https://www.w3.org/TR/FileAPI/
[FIPS-180-4]
FIPS PUB180-4180-4:Secure HashStandardStandard (SHS). U.S. Department of Commerce/National Institute of Standards and Technology.August 2015. National Standard.URL:https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
[GETUSERMEDIA]
Media Capture and Streams. Cullen Jennings; Bernard Aboba; Jan-Ivar Bruaroey; Henrik Boström; youenn fablet; Daniel Burnett; Adam Bergkvist; Anant Narayanan. W3C.21 January 202119 December 2024.W3C Candidate RecommendationCRD. URL:https://www.w3.org/TR/mediacapture-streams/
[hr-time]
High ResolutionTime Level 2Time.Ilya GrigorikYoav Weiss. W3C.217November20192024. W3CRecommendationWorking Draft. URL:https://www.w3.org/TR/hr-time-2/org/TR/hr-time-3/
[HTML]
HTML Standard. Anne van Kesteren; Domenic Denicola;Dominic Farolino;Ian Hickson; Philip Jägenstedt; Simon Pieters. WHATWG. Living Standard. URL:https://html.spec.whatwg.org/multipage/
[IANA-HASH-FUNCTION]
Hash Function Textual Names. IANA. URL:https://www.iana.org/assignments/hash-function-text-names/hash-function-text-names.xml
[IANA-RTP-2]
RTP Payload Format media types. IANA. URL:https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-2
[INFRA]
Infra Standard. Anne van Kesteren; Domenic Denicola. WHATWG. Living Standard. URL:https://infra.spec.whatwg.org/
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL:https://tools.ietf.org/html/rfc2119https://www.rfc-editor.org/rfc/rfc2119
[RFC3550]
RTP: A Transport Protocol for Real-Time Applications. H. Schulzrinne; S. Casner; R. Frederick; V. Jacobson. IETF. July 2003. Internet Standard. URL:https://tools.ietf.org/html/rfc3550https://www.rfc-editor.org/rfc/rfc3550
[RFC3890]
A Transport Independent Bandwidth Modifier for the Session Description Protocol (SDP). M. Westerlund. IETF. September 2004. Proposed Standard. URL:https://tools.ietf.org/html/rfc3890https://www.rfc-editor.org/rfc/rfc3890
[RFC3986]
Uniform Resource Identifier (URI): Generic Syntax. T. Berners-Lee; R. Fielding; L. Masinter. IETF. January 2005. Internet Standard. URL:https://tools.ietf.org/html/rfc3986
[RFC4566]
SDP: Session Description Protocol. M. Handley; V. Jacobson; C. Perkins. IETF. July 2006. Proposed Standard. URL:https://tools.ietf.org/html/rfc4566https://www.rfc-editor.org/rfc/rfc4566
[RFC4572]
Connection-Oriented Media Transport over the Transport Layer Security (TLS) Protocol in the Session Description Protocol (SDP). J. Lennox. IETF. July 2006. Proposed Standard. URL:https://tools.ietf.org/html/rfc4572https://www.rfc-editor.org/rfc/rfc4572
[RFC5245]
Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal for Offer/Answer Protocols. J. Rosenberg. IETF. April 2010. Proposed Standard. URL:https://tools.ietf.org/html/rfc5245https://www.rfc-editor.org/rfc/rfc5245
[RFC5246]
The Transport Layer Security (TLS) Protocol Version 1.2. T. Dierks; E. Rescorla. IETF. August 2008. Proposed Standard. URL:https://tools.ietf.org/html/rfc5246https://www.rfc-editor.org/rfc/rfc5246
[RFC5285]
A General Mechanism for RTP Header Extensions. D. Singer; H. Desineni. IETF. July 2008. Proposed Standard. URL:https://tools.ietf.org/html/rfc5285https://www.rfc-editor.org/rfc/rfc5285
[RFC5389]
Session Traversal Utilities for NAT (STUN). J. Rosenberg; R. Mahy; P. Matthews; D. Wing. IETF. October 2008. Proposed Standard. URL:https://tools.ietf.org/html/rfc5389https://www.rfc-editor.org/rfc/rfc5389
[RFC5506]
Support for Reduced-Size Real-Time Transport Control Protocol (RTCP): Opportunities and Consequences. I. Johansson; M. Westerlund. IETF. April 2009. Proposed Standard. URL:https://tools.ietf.org/html/rfc5506https://www.rfc-editor.org/rfc/rfc5506
[RFC5888]
The Session Description Protocol (SDP) Grouping Framework. G. Camarillo; H. Schulzrinne. IETF. June 2010. Proposed Standard. URL:https://tools.ietf.org/html/rfc5888https://www.rfc-editor.org/rfc/rfc5888
[RFC6464]
A Real-time Transport Protocol (RTP) Header Extension for Client-to-Mixer Audio Level Indication. J. Lennox, Ed.; E. Ivov; E. Marocco. IETF. December 2011. Proposed Standard. URL:https://tools.ietf.org/html/rfc6464https://www.rfc-editor.org/rfc/rfc6464
[RFC6465]
A Real-time Transport Protocol (RTP) Header Extension for Mixer-to-Client Audio Level Indication. E. Ivov, Ed.; E. Marocco, Ed.; J. Lennox. IETF. December 2011. Proposed Standard. URL:https://tools.ietf.org/html/rfc6465https://www.rfc-editor.org/rfc/rfc6465
[RFC6544]
TCP Candidates with Interactive Connectivity Establishment (ICE). J. Rosenberg; A. Keranen; B. B. Lowekamp; A. B. Roach. IETF. March 2012. Proposed Standard. URL:https://tools.ietf.org/html/rfc6544https://www.rfc-editor.org/rfc/rfc6544
[RFC7064]
URI Scheme for the Session Traversal Utilities for NAT (STUN) Protocol. S. Nandakumar; G. Salgueiro; P. Jones; M. Petit-Huguenin. IETF. November 2013. Proposed Standard. URL:https://tools.ietf.org/html/rfc7064https://www.rfc-editor.org/rfc/rfc7064
[RFC7065]
Traversal Using Relays around NAT (TURN) Uniform Resource Identifiers. M. Petit-Huguenin; S. Nandakumar; G. Salgueiro; P. Jones. IETF. November 2013. Proposed Standard. URL:https://tools.ietf.org/html/rfc7065https://www.rfc-editor.org/rfc/rfc7065
[RFC7656]
A Taxonomy of Semantics and Mechanisms for Real-Time Transport Protocol (RTP) Sources. J. Lennox; K. Gross; S. Nandakumar; G. Salgueiro; B. Burman, Ed..IETF. November 2015. Informational. URL:https://tools.ietf.org/html/rfc7656https://www.rfc-editor.org/rfc/rfc7656
[RFC7675]
Session Traversal Utilities for NAT (STUN) Usage for Consent Freshness. M. Perumal; D. Wing; R. Ravindranath; T. Reddy; M. Thomson. IETF. October 2015. Proposed Standard. URL:https://tools.ietf.org/html/rfc7675https://www.rfc-editor.org/rfc/rfc7675
[RFC7874]
WebRTC Audio Codec and Processing Requirements. JM. Valin; C. Bran. IETF. May 2016. Proposed Standard. URL:https://tools.ietf.org/html/rfc7874https://www.rfc-editor.org/rfc/rfc7874
[RFC8174]
Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words. B. Leiba. IETF. May 2017. Best Current Practice. URL:https://tools.ietf.org/html/rfc8174https://www.rfc-editor.org/rfc/rfc8174
[RFC8261]
Datagram Transport Layer Security (DTLS) Encapsulation of SCTP Packets. M. Tuexen; R. Stewart; R. Jesup; S. Loreto. IETF. November 2017. Proposed Standard. URL:https://tools.ietf.org/html/rfc8261https://www.rfc-editor.org/rfc/rfc8261
[RFC8445]
Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal. A. Keranen; C. Holmberg; J. Rosenberg. IETF. July 2018. Proposed Standard. URL:https://tools.ietf.org/html/rfc8445https://www.rfc-editor.org/rfc/rfc8445
[RFC8656]
Traversal Using Relays around NAT (TURN): Relay Extensions to Session Traversal Utilities for NAT (STUN). T. Reddy, Ed.; A. Johnston, Ed.; P. Matthews; J. Rosenberg. IETF. February 2020. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc8656
[RFC8826]
Security Considerationsfor WebRTCfor WebRTC. E. Rescorla. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8826https://www.rfc-editor.org/rfc/rfc8826
[RFC8829]
JavaScript Session Establishment Protocol (JSEP). J. Uberti; C. Jennings; E. Rescorla, Ed.. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8829
[RFC8831]
WebRTC Data Channels. R. Jesup; S. Loreto; M. Tüxen. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8831https://www.rfc-editor.org/rfc/rfc8831
[RFC8832]
WebRTC Data Channel Establishment Protocol. R. Jesup; S. Loreto; M. Tüxen. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8832https://www.rfc-editor.org/rfc/rfc8832
[RFC8834]
Media Transport and Use of RTP in WebRTC. C. Perkins; M. Westerlund; J. Ott. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8834https://www.rfc-editor.org/rfc/rfc8834
[RFC8835]
Transports for WebRTC. H. Alvestrand. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8835https://www.rfc-editor.org/rfc/rfc8835
[RFC8838]
Trickle ICE: Incremental Provisioning of Candidates for the Interactive Connectivity Establishment (ICE) Protocol. E. Ivov; J. Uberti; P. Saint-Andre. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8838https://www.rfc-editor.org/rfc/rfc8838
[RFC8841]
Session Description Protocol (SDP) Offer/Answer Procedures for Stream Control Transmission Protocol (SCTP) over Datagram Transport Layer Security (DTLS) Transport. C. Holmberg; R. Shpount; S. Loreto; G. Camarillo. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8841https://www.rfc-editor.org/rfc/rfc8841
[RFC8843]
Negotiating Media Multiplexing Using the Session Description Protocol (SDP). C. Holmberg; H. Alvestrand; C. Jennings. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8843https://www.rfc-editor.org/rfc/rfc8843
[RFC8851]
RTP Payload Format Restrictions. A.B. Roach, Ed..IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8851https://www.rfc-editor.org/rfc/rfc8851
[RFC8853]
Using Simulcast in Session Description Protocol (SDP) and RTP Sessions. B. Burman; M. Westerlund; S. Nandakumar; M. Zanaty. IETF. January 2021. Proposed Standard. URL:https://tools.ietf.org/html/rfc8853https://www.rfc-editor.org/rfc/rfc8853
[RFC8863]
Interactive Connectivity Establishment Patiently Awaiting Connectivity (ICE PAC). C. Holmberg; J. Uberti. IETF. January 2021. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc8863
[RFC9429]
JavaScript Session Establishment Protocol (JSEP). J. Uberti; C. Jennings; E. Rescorla, Ed. IETF. April 2024. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc9429
[SDP]
An Offer/Answer Model with Session Description Protocol (SDP). J. Rosenberg; H. Schulzrinne. IETF. June 2002. Proposed Standard. URL:https://tools.ietf.org/html/rfc3264https://www.rfc-editor.org/rfc/rfc3264
[STUN-PARAMETERS]
STUN Error Codes. IETF. IANA. April 2011. IANA Parameter Assignment. URL:https://www.iana.org/assignments/stun-parameters/stun-parameters.xhtml#stun-parameters-6
[WebCryptoAPI]
Web Cryptography API. Mark Watson. W3C. 26 January 2017. W3C Recommendation. URL:https://www.w3.org/TR/WebCryptoAPI/
[WEBIDL]
Web IDL. Boris Zbarsky. W3C. 15 December 2016. W3C Editor's Draft. URL:https://heycam.github.io/webidl/
Web IDL Standard. Edgar Chen; Timothy Gu. WHATWG. Living Standard. URL:https://webidl.spec.whatwg.org/
[WEBRTC-STATS]
Identifiers for WebRTC's Statistics API. Harald Alvestrand; Varun Singh; Henrik Boström. W3C.20 January 20216 March 2025.W3C Candidate RecommendationCRD. URL:https://www.w3.org/TR/webrtc-stats/
[X509V3]
ITU-T Recommendation X.509 version 3 (1997). "Information Technology - Open Systems Interconnection - The Directory Authentication Framework"  ISO/IEC 9594-8:1997.. ITU.
[X690]
Recommendation X.690 — Information Technology — ASN.1 Encoding Rules — Specification of Basic Encoding Rules (BER), Canonical Encoding Rules (CER), and Distinguished Encoding Rules (DER). ITU. URL:https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf

C.2Informative references

[API-DESIGN-PRINCIPLES]
Web Platform Design Principles. Martin Thomson; Jeffrey Yasskin. W3C. 6 March 2025. W3C Working Group Note. URL:https://www.w3.org/TR/design-principles/
[INDEXEDDB]
Indexed Database API. Nikunj Mehta; Jonas Sicking; Eliot Graff; Andrei Popescu; Jeremy Orlow; Joshua Bell. W3C. 8 January 2015. W3C Recommendation. URL:https://www.w3.org/TR/IndexedDB/
[RFC4103]
RTP Payload for Text Conversation. G. Hellstrom; P. Jones. IETF. June 2005. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc4103
[RFC6236]
Negotiation of Generic Image Attributes in the Session Description Protocol (SDP). I. Johansson; K. Jung. IETF. May 2011. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc6236
[RFC7728]
RTP Stream Pause and Resume. B. Burman; A. Akram; R. Even; M. Westerlund. IETF. February 2016. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc7728
[RFC8825]
Overview: Real-Time Protocols for Browser-Based Applications. H. Alvestrand. IETF. January 2021. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc8825
[RFC8827]
WebRTC Security Architecture. E. Rescorla. IETF. January 2021. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc8827
[RFC8828]
WebRTC IP Address Handling Requirements. J. Uberti; G. Shieh. IETF. January 2021. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc8828


[8]ページ先頭

©2009-2025 Movatter.jp