WebRTC 1.0: Real-Time Communication Between Browsers
W3C Recommendation
- This version:
- https://www.w3.org/TR/2021/REC-webrtc-20210126/
- Latest published version:
- https://www.w3.org/TR/webrtc/
- Latest editor's draft:
- https://w3c.github.io/webrtc-pc/
- 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
- Previous version:
- https://www.w3.org/TR/2020/PR-webrtc-20201215/
- Editors:
- Former editors:
- Participate:
- GitHub w3c/webrtc-pc
- File a bug
- Commit history
- Pull requests
- Participate:
- Mailing list
Please check the errata for any errors or issues reported since publication.
See also translations.
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 following
Copyright:
© 2011-2021 W3C® (MIT, ERCIM,
Keio, Beihang). W3C liability,
trademark and permissive 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. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.
The API is based on preliminary work done in the WHATWG.
Its associated test suite is used to build an implementation report of the API.
This document was published by the Web Real-Time Communications Working Group as a Recommendation.
GitHub Issues are preferred for discussion of this specification. Alternatively, you can send comments to our mailing list. Please send them to public-webrtc@w3.org (archives).
A W3C Recommendation is a specification that, after extensive consensus-building, has received the endorsement of the W3C and its Members. W3C recommends the wide deployment of this specification as a standard for the Web. Future updates to this Recommendation may incorporate new features.
This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
This document is governed by the 15 September 2020 W3C Process Document.
1. Introduction
This section is non-normative.
There are a number of facets to peer-to-peer communications and video-conferencing in HTML covered by this specification:
- Connecting to remote peers using NAT-traversal technologies such as ICE, STUN, and TURN.
- Sending the locally-produced tracks to remote peers and receiving tracks from remote peers.
- Sending arbitrary data directly to remote peers.
This document defines the APIs used for these features. This specification is being developed in conjunction with a protocol specification developed by the IETF RTCWEB group and an API specification to get access to local media devices [GETUSERMEDIA] developed by the WebRTC Working Group. An overview of the system can be found in [RFC8825] and [RFC8826].
2. Conformance
As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The key words MAY, MUST, MUST NOT, and SHOULD in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.
This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)
Implementations that use ECMAScript to implement the APIs defined in this specification MUST implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL], as this specification uses that specification and terminology.
3. Terminology
The EventHandler interface, representing a callback used for event
handlers, is defined in [HTML].
The concepts queue a task and networking task source are defined in [HTML].
The concept fire an event is defined in [DOM].
The terms event, event handlers and event handler event types are defined in [HTML].
Performance.timeOrigin and Performance.now() are defined in
[hr-time].
The terms serializable objects, serialization steps, and deserialization steps are defined in [HTML].
The terms MediaStream, MediaStreamTrack, and
MediaStreamConstraints are defined in [GETUSERMEDIA]. Note that
MediaStream is extended in § 9.2
MediaStream
in this document while MediaStreamTrack is extended in § 9.3
MediaStreamTrack
in this document.
The term Blob is defined in [FILEAPI].
The term media description is defined in [RFC4566].
The term media transport is defined in [RFC7656].
The term generation is defined in [RFC8838] Section 2.
The terms stats object and monitored object are defined in [WEBRTC-STATS].
When referring to exceptions, the terms throw and created are defined in [WEBIDL].
The callback VoidFunction is defined in [WEBIDL].
The term "throw" is used as specified in [INFRA]: it terminates the current processing steps.
The terms fulfilled, rejected, resolved, pending and settled used in the context of Promises are defined in [ECMASCRIPT-6.0].
The terms bundle, bundle-only and bundle-policy are defined in [RFC8829].
The AlgorithmIdentifier is defined in [WebCryptoAPI].
The general principles for Javascript APIs apply, including the
principle of run-to-completion
and no-data-races as defined in [API-DESIGN-PRINCIPLES]. That is,
while a task is running, external events do not influence what's
visible to the Javascript application. For example, the amount of data
buffered on a data channel will increase due to "send" calls while
Javascript is executing, and the decrease due to packets being sent
will be visible after a task checkpoint.
It is the responsibility of the user agent to make sure the set of
values presented to the application is consistent - for instance that
getContributingSources() (which is synchronous) returns values for all
sources measured at the same time.
4. Peer-to-peer connections
4.1 Introduction
An instance allows an application to establish
peer-to-peer communications with another RTCPeerConnection
instance in another browser, or to another endpoint implementing the
required protocols. Communications are coordinated by the exchange of
control messages (called a signaling protocol) over a signaling
channel which is provided by unspecified means, but generally by a
script in the page via the server, e.g. using Web
Sockets or RTCPeerConnectionXMLHttpRequest [xhr].
4.2 Configuration
4.2.1
RTCConfiguration Dictionary
The defines a set of parameters to configure
how the peer-to-peer communication established via
RTCConfiguration is established or re-established.
RTCPeerConnection
WebIDLdictionaryRTCConfiguration{ sequence<RTCIceServer>iceServers;RTCIceTransportPolicyiceTransportPolicy;RTCBundlePolicybundlePolicy;RTCRtcpMuxPolicyrtcpMuxPolicy; sequence<RTCCertificate>certificates; [EnforceRange] octeticeCandidatePoolSize= 0; };
Dictionary RTCConfiguration Members
RTCConfiguration-
iceServersof type sequence<>RTCIceServer -
An array of objects describing servers available to be used by ICE, such as STUN and TURN servers.
-
iceTransportPolicyof type.RTCIceTransportPolicy -
Indicates which candidates the ICE Agent is allowed to use.
-
bundlePolicyof type.RTCBundlePolicy -
Indicates which media-bundling policy to use when gathering ICE candidates.
-
rtcpMuxPolicyof type.RTCRtcpMuxPolicy -
Indicates which rtcp-mux policy to use when gathering ICE candidates.
-
certificatesof type sequence<>RTCCertificate -
A set of certificates that the
uses to authenticate.RTCPeerConnectionValid values for this parameter are created through calls to the
generateCertificate()function.Although any given DTLS connection will use only one certificate, this attribute allows the caller to provide multiple certificates that support different algorithms. The final certificate will be selected based on the DTLS handshake, which establishes which certificates are allowed. The
implementation selects which of the certificates is used for a given connection; how certificates are selected is outside the scope of this specification.RTCPeerConnectionNoteExisting implementations only utilize the first certificate provided; the others are ignored.
If this value is absent, then a default set of certificates is generated for each
instance.RTCPeerConnectionThis option allows applications to establish key continuity. An
can be persisted in [INDEXEDDB] and reused. Persistence and reuse also avoids the cost of key generation.RTCCertificateThe value for this configuration option cannot change after its value is initially selected.
-
iceCandidatePoolSizeof type octet, defaulting to0 -
Size of the prefetched ICE pool as defined in [RFC8829] (section 3.5.4. and section 4.1.1.).
4.2.2
RTCIceCredentialType Enum
WebIDLenumRTCIceCredentialType{ "password" };
| Enumeration description | |
|---|---|
password
|
The credential is a long-term authentication username and password, as described in [RFC5389], Section 10.2. |
4.2.3
RTCIceServer Dictionary
The dictionary is used to describe the STUN and
TURN servers that can be used by the ICE Agent to establish a
connection with a peer.
RTCIceServer
WebIDLdictionaryRTCIceServer{ required (DOMString or sequence<DOMString>)urls; DOMStringusername; DOMStringcredential;RTCIceCredentialTypecredentialType= "password"; };
Dictionary RTCIceServer Members
RTCIceServer-
urlsof type (DOMString or sequence<DOMString>), required -
STUN or TURN URI(s) as defined in [RFC7064] and [RFC7065] or other URI types.
-
usernameof type DOMString -
If this
object represents a TURN server, andRTCIceServeris "credentialType", then this attribute specifies the username to use with that TURN server.password -
credentialof typeDOMString -
If this
object represents a TURN server, then this attribute specifies the credential to use with that TURN server.RTCIceServerIf
is "credentialType",passwordrepresents a long-term authentication password, as described in [RFC5389], Section 10.2.credentialNoteTo support additional values of
,credentialTypemay evolve in future as a union.credential -
credentialTypeof type, defaulting to "RTCIceCredentialType"password -
If this
object represents a TURN server, then this attribute specifies how credential should be used when that TURN server requests authorization.RTCIceServer
An example array of objects is:
RTCIceServer
[
{urls: 'stun:stun1.example.net'},
{urls: ['turns:turn.example.org', 'turn:turn.example.net'],
username: 'user',
credential: 'myPassword',
credentialType: 'password'},
];
4.2.4
RTCIceTransportPolicy Enum
As described in [RFC8829] (section 4.1.1.), if
the member of the
iceTransportPolicy is specified, it defines the ICE candidate policy [RFC8829] (section 3.5.3.) the
browser uses to surface the permitted candidates to the
application; only these candidates will be used for connectivity
checks.
RTCConfiguration
WebIDLenumRTCIceTransportPolicy{ "relay", "all" };
| Enumeration description (non-normative) | |
|---|---|
relay
|
The ICE Agent uses only media relay candidates such as candidates passing through a TURN server. Note
This can be used to prevent the remote endpoint from
learning the user's IP addresses, which may be desired in
certain use cases. For example, in a "call"-based
application, the application may want to prevent an
unknown caller from learning the callee's IP addresses
until the callee has consented in some way.
|
all
|
The ICE Agent can use any type of candidate when this value is specified. Note
The implementation can still use its own candidate
filtering policy in order to limit the IP addresses
exposed to the application, as noted in the description
of ..
|
4.2.5
RTCBundlePolicy Enum
As described in [RFC8829] (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" };
| Enumeration description (non-normative) | |
|---|---|
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.6
RTCRtcpMuxPolicy Enum
As described in [RFC8829] (section 4.1.1.), the
affects what ICE candidates are gathered to
support non-multiplexed RTCP. The only value defined in this spec
is "RTCRtcpMuxPolicy".
require
WebIDL enumRTCRtcpMuxPolicy{ "require" };
| Enumeration description (non-normative) | |
|---|---|
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.7 Offer/Answer Options
These dictionaries describe the options that can be used to control the offer/answer creation process.
WebIDLdictionary RTCOfferAnswerOptions {};
Dictionary RTCOfferAnswerOptions Members
WebIDL dictionaryRTCOfferOptions:RTCOfferAnswerOptions{ booleaniceRestart= false; };
Dictionary RTCOfferOptions Members
-
iceRestartof type boolean, defaulting tofalse -
When the value of this dictionary member is
true, or the relevantobject's [[LocalIceCredentialsToReplace]] slot is not empty, then the generated description will have ICE credentials that are different from the current credentials (as visible in theRTCPeerConnectionattribute's SDP). Applying the generated description will restart ICE, as described in section 9.1.1.1 of [RFC5245].currentLocalDescriptionWhen the value of this dictionary member is
false, and the relevantobject's [[LocalIceCredentialsToReplace]] slot is empty, and theRTCPeerConnectionattribute has valid ICE credentials, then the generated description will have the same ICE credentials as the current value from thecurrentLocalDescriptionattribute.currentLocalDescriptionNotePerforming an ICE restart is recommended when
transitions to "iceConnectionState". An application may additionally choose to listen for thefailedtransition to "iceConnectionState" and then use other sources of information (such as usingdisconnectedto measure if the number of bytes sent or received over the next couple of seconds increases) to determine whether an ICE restart is advisable.getStats
The RTCAnswerOptions dictionary describe options
specific to session description of type ""
(none in this version of the specification).
answer
WebIDLdictionaryRTCAnswerOptions:RTCOfferAnswerOptions{};
4.3 State Definitions
4.3.1
RTCSignalingState Enum
WebIDLenumRTCSignalingState{ "stable", "have-local-offer", "have-remote-offer", "have-local-pranswer", "have-remote-pranswer", "closed" };
| Enumeration description | |
|---|---|
stable
|
There is no offer/answer exchange in progress. This is also the initial state, in which case the local and remote descriptions are empty. |
have-local-offer
|
A local description, of type "", has
been successfully applied.
|
have-remote-offer
|
A remote description, of type "", has
been successfully applied.
|
have-local-pranswer
|
A remote description of type "" has
been successfully applied and a local description of type
"" has been successfully applied.
|
have-remote-pranswer
|
A local description of type "" has been
successfully applied and a remote description of type
"" has been successfully applied.
|
closed
|
The has been closed; its
[[IsClosed]] slot is true.
|
An example set of transitions might be:
- Caller transition:
-
- new RTCPeerConnection(): "
"stable - setLocalDescription(offer):
"
"have-local-offer - setRemoteDescription(pranswer):
"
"have-remote-pranswer - setRemoteDescription(answer):
"
"stable
- new RTCPeerConnection(): "
- Callee transition:
-
- new RTCPeerConnection(): "
"stable - setRemoteDescription(offer):
"
"have-remote-offer - setLocalDescription(pranswer):
"
"have-local-pranswer - setLocalDescription(answer): "
"stable
- new RTCPeerConnection(): "
4.3.2
RTCIceGatheringState Enum
WebIDLenumRTCIceGatheringState{ "new", "gathering", "complete" };
| Enumeration description | |
|---|---|
new
|
Any of the s are in the
"" gathering state and none of
the transports are in the
"" state, or there are no
transports.
|
gathering
|
Any of the s are in the
"" state.
|
complete
|
At least one exists, and all
s are in the
"" gathering state.
|
The set of transports considered is the set of transports presently referenced by the PeerConnection's set of transceivers.
4.3.3
RTCPeerConnectionState Enum
WebIDLenumRTCPeerConnectionState{ "closed", "failed", "disconnected", "new", "connecting", "connected" };
| Enumeration description | |
|---|---|
closed
|
The object's [[IsClosed]]
slot is true.
|
failed
|
The previous state doesn't apply and any
s are in the
"" state or any
s are in the
"" state.
|
disconnected
|
None of the previous states apply and any
s are in the
"" state.
|
new
|
None of the previous states apply and all
s are in the
"" or
"" state, and all
s are in the
"" or
"" state, or there are no
transports.
|
connecting
|
None of the previous states apply and any
is in the
"" state or any
is in the
"" state.
|
connected
|
None of the previous states apply and all
s are in the
"",
"" or
"" state, and all
s are in the
"" or
"" state.
|
The set of transports considered is the set of transports presently referenced by the PeerConnection's set of transceivers.
4.3.4
RTCIceConnectionState Enum
WebIDLenumRTCIceConnectionState{ "closed", "failed", "disconnected", "new", "checking", "completed", "connected" };
| Enumeration description | |
|---|---|
closed
|
The object's [[IsClosed]]
slot is true.
|
failed
|
The previous state doesn't apply and any
s are in the
"" state.
|
disconnected
|
None of the previous states apply and any
s are in the
"" state.
|
new
|
None of the previous states apply and all
s are in the
"" or
"" state, or there are no
transports.
|
checking
|
None of the previous states apply and any
s are in the
"" or
"" state.
|
completed
|
None of the previous states apply and all
s are in the
"" or
"" state.
|
connected
|
None of the previous states apply and all
s are in the
"",
"" or
"" state.
|
The set of transports considered is the set of transports presently referenced by the PeerConnection's set of transceivers.
Note that if an is discarded as a result of
signaling (e.g. RTCP mux or bundling), or created as a result of
signaling (e.g. adding a new media description), the state
may advance directly from one state to another.
RTCIceTransport
4.4 RTCPeerConnection Interface
The [RFC8829] specification, as a whole, describes the details of how
the operates. References to specific
subsections of [RFC8829] are provided as appropriate.
RTCPeerConnection
4.4.1 Operation
Calling new
creates an
(configuration)RTCPeerConnection object.
RTCPeerConnection
configuration. contains
information used to find and access the servers used by ICE. The
application can supply multiple servers of each type, and any TURN
server MAY also be used as a STUN server for the purposes of
gathering server reflexive candidates.
iceServers
An object has a signaling state, a
connection state, an ICE gathering state, and
an ICE connection state. These are initialized when the
object is created.
RTCPeerConnection
The ICE protocol implementation of an is
represented by an ICE agent [RFC5245]. Certain
RTCPeerConnection methods involve interactions with the ICE
Agent, namely RTCPeerConnection, addIceCandidate,
setConfiguration, setLocalDescription and setRemoteDescription.
These interactions are described in the relevant sections in this
document and in [RFC8829]. The ICE Agent also provides
indications to the user agent when the state of its internal
representation of an close changes, as described in
§ 5.6
RTCIceTransportRTCIceTransport Interface
.
The task source for the tasks listed in this section is the networking task source.
The state of the SDP negotiation is represented by the signaling
state and the internal variables
[[CurrentLocalDescription]],
[[CurrentRemoteDescription]],
[[PendingLocalDescription]] and
[[PendingRemoteDescription]]. These are only set inside the
and setLocalDescription operations,
and modified by the setRemoteDescription operation and the surface a candidate procedure. In each case, all the
modifications to all the five variables are completed before the
procedures fire any events or invoke any callbacks, so the
modifications are made visible at a single point in time.
addIceCandidate
As one of the unloading document cleanup steps, run the following steps:
-
Let window be document's relevant global object.
-
For each
object connection whose relevant global object is window, close the connection with connection and the valueRTCPeerConnectiontrue.
4.4.1.1 Constructor
When the RTCPeerConnection.constructor() is
invoked, the user agent MUST run the following steps:
-
If any of the steps enumerated below fails for a reason not specified here, throw an
UnknownErrorwith theattribute set to an appropriate description.message -
Let connection be a newly created
object.RTCPeerConnection -
Let connection have a [[DocumentOrigin]] internal slot, initialized to the relevant settings object's origin.
- Let configuration be the method's first argument.
-
If the
value in configuration is non-empty, run the following steps for each certificate in certificates:certificates-
If the value of certificate.
is less than the current time, throw anexpiresInvalidAccessError. -
If certificate.[[Origin]] is not same origin with connection.[[DocumentOrigin]], throw an
InvalidAccessError. -
Store certificate.
-
-
Else, generate one or more new
instances with thisRTCCertificateinstance and store them. This MAY happen asynchronously and the value ofRTCPeerConnectionremainscertificatesundefinedfor 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. -
Initialize connection's ICE Agent.
-
If the value of configuration.
isiceTransportPolicyundefined, set it to "".all -
If the value of configuration.
isbundlePolicyundefined, set it to "".balanced -
If the value of configuration.
isrtcpMuxPolicyundefined, set it to "".require -
Let connection have a [[Configuration]] internal slot. Set the configuration specified by configuration.
-
Let connection have an [[IsClosed]] internal slot, initialized to
false. -
Let connection have a [[NegotiationNeeded]] internal slot, initialized to
false. -
Let connection have an [[SctpTransport]] internal slot, initialized to
null. -
Let connection have an [[Operations]] internal slot, representing an operations chain, initialized to an empty list.
-
Let connection have a [[UpdateNegotiationNeededFlagOnEmptyChain]] internal slot, initialized to
false. -
Let connection have an [[LastCreatedOffer]] internal slot, initialized to
"". -
Let connection have an [[LastCreatedAnswer]] internal slot, initialized to
"". -
Let connection have an [[EarlyCandidates]] internal slot, initialized to an empty list.
-
Set connection's signaling state to "
".stable -
Set connection's ICE connection state to "
".new -
Set connection's ICE gathering state to "
".new -
Set connection's connection state to "
".new -
Let connection have a [[PendingLocalDescription]] internal slot, initialized to
null. -
Let connection have a [[CurrentLocalDescription]] internal slot, initialized to
null. -
Let connection have a [[PendingRemoteDescription]] internal slot, initialized to
null. -
Let connection have a [[CurrentRemoteDescription]] internal slot, initialized to
null. -
Let connection have a [[LocalIceCredentialsToReplace]] internal slot, initialized to an empty set.
-
Return connection.
4.4.1.2 Chain an asynchronous operation
An object has an operations
chain, [[Operations]], which ensures that only one
asynchronous operation in the chain executes concurrently. If
subsequent calls are made while the returned promise of a
previous call is still not settled, they are added to the
chain and executed when all the previous calls have finished
executing and their promises have settled.
RTCPeerConnection
To chain an operation to an
object's operations chain, run the
following steps:
RTCPeerConnection
-
Let connection be the
object.RTCPeerConnection -
If connection.[[IsClosed]] is
true, return a promise rejected with a newly createdInvalidStateError. -
Let operation be the operation to be chained.
-
Let p be a new promise.
-
Append operation to [[Operations]].
-
If the length of [[Operations]] is exactly 1, execute operation.
-
Upon fulfillment or rejection of the promise returned by the operation, run the following steps:
-
If connection.[[IsClosed]] is
true, abort these steps. -
If the promise returned by operation was fulfilled with a value, fulfill p with that value.
-
If the promise returned by operation was rejected with a value, reject p with that value.
-
Upon fulfillment or rejection of p, execute the following steps:
-
If connection.[[IsClosed]] is
true, abort these steps. -
Remove the first element of [[Operations]].
-
If [[Operations]] is non-empty, execute the operation represented by the first element of [[Operations]], and abort these steps.
-
If connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] is
false, abort these steps. -
Set connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] to
false. -
Update the negotiation-needed flag for connection.
-
-
-
Return p.
4.4.1.3 Update the connection state
An object has an aggregated connection
state. Whenever the state of an RTCPeerConnection changes
or when the [[IsClosed]] slot turns RTCDtlsTransporttrue,
the user agent MUST update the connection state by queueing a
task that runs the following steps:
-
Let connection be this
object.RTCPeerConnection -
Let newState be the value of deriving a new state value as described by the
enum.RTCPeerConnectionState -
If connection's connection state is equal to newState, abort these steps.
-
Let connection's connection state be newState.
-
Fire an event named
at connection.connectionstatechange
4.4.1.4 Update the ICE gathering state
To update the ICE
gathering state of an instance
connection, the user agent MUST queue a task that runs
the following steps:
RTCPeerConnection
-
If connection.[[IsClosed]] is
true, abort these steps. -
Let newState be the value of deriving a new state value as described by the
enum.RTCIceGatheringState -
If connection's ICE gathering state is equal to newState, abort these steps.
-
Set connection's ICE gathering state to newState.
-
Fire an event named
at connection.icegatheringstatechange -
If newState is "
", fire an event namedcompleteusing theicecandidateinterface with the candidate attribute set toRTCPeerConnectionIceEventnullat connection.NoteThe null candidate event is fired to ensure legacy compatibility. New code should monitor the gathering state ofand/orRTCIceTransport.RTCPeerConnection
4.4.1.5 Set the session description
To
set a local session description description on
an object connection, set the session description
description on connection with the additional
value RTCPeerConnectionfalse.
To
set a remote session description description
on an object connection, set the session description
description on connection with the additional
value RTCPeerConnectiontrue.
To set
a session description description on an
object connection, given a
remote boolean, run the following steps:
RTCPeerConnection
-
Let p be a new promise.
-
If description.
is "type" and connection's signaling state is either "rollback", "stable", or "have-local-pranswer", then reject p with a newly createdhave-remote-pranswerInvalidStateErrorand abort these steps. -
Let jsepSetOfTransceivers be a shallow copy of connection's set of transceivers.
-
In parallel, start the process to apply description as described in [RFC8829] (section 5.5. and section 5.6.), with these additional restrictions:
-
Use jsepSetOfTransceivers as the source of truth with regard to what "RtpTransceivers" exist, and their [[JsepMid]] internal slot as their "mid property".
-
If remote is
true, validate back-to-back offers as if answers were applied in between, by running the check for subsequent offers as if it were in stable state. -
If applying description leads to modifying a transceiver transceiver, and transceiver.[[Sender]].[[SendEncodings]] is non-empty, and not equal to the encodings that would result from processing description, the process of applying description fails. This specification does not allow remotely initiated RID renegotiation.
-
If the process to apply description fails for any reason, then the user agent MUST queue a task that runs the following steps:
-
If connection.[[IsClosed]] is
true, then abort these steps. -
If description.
is invalid for the current signaling state of connection as described in [RFC8829] (section 5.5. and section 5.6.), then reject p with a newly createdtypeInvalidStateErrorand abort these steps. -
If the content of description is not valid SDP syntax, then reject p with an
(withRTCErrorset to "errorDetail" and thesdp-syntax-errorattribute set to the line number in the SDP where the syntax error was detected) and abort these steps.sdpLineNumber -
If remote is
true, the connection'sisRTCRtcpMuxPolicyand the description does not use RTCP mux, then reject p with a newly createdrequireInvalidAccessErrorand abort these steps. -
If the description attempted to renegotiate RIDs, as described above, then reject p with a newly created
InvalidAccessErrorand abort these steps. -
If the content of description is invalid, then reject p with a newly created
InvalidAccessErrorand abort these steps. -
For all other errors, reject p with a newly created
OperationError.
-
-
If description is applied successfully, the user agent MUST queue a task that runs the following steps:
-
If connection.[[IsClosed]] is
true, then abort these steps. -
If remote is
trueand description is of type "", then if anyofferaddTrack()methods succeeded during the process to apply description, abort these steps and start the process over as if they had succeeded prior, to include the extra transceiver(s) in the process. -
If description is of type "
" and the signaling state of connection is "offer" then for each transceiver in connection's set of transceivers, run the following steps:stable-
Set transceiver.[[Sender]].[[LastStableStateSenderTransport]] to transceiver.[[Sender]].[[SenderTransport]].
-
Set transceiver.[[Receiver]].[[LastStableStateReceiverTransport]] to transceiver.[[Receiver]].[[ReceiverTransport]].
-
Set transceiver.[[Receiver]].[[LastStableStateAssociatedRemoteMediaStreams]] to transceiver.[[Receiver]].[[AssociatedRemoteMediaStreams]].
-
Set transceiver.[[Receiver]].[[LastStableStateReceiveCodecs]] to transceiver.[[Receiver]].[[ReceiveCodecs]].
-
-
If remote is
false, then run one of the following steps:-
If description is of type "
", set connection.[[PendingLocalDescription]] to a newofferobject constructed from description, set connection's signaling state to "RTCSessionDescription", and release early candidates.have-local-offer -
If description is of type "
", then this completes an offer answer negotiation. Set connection.[[CurrentLocalDescription]] to a newanswerobject constructed from description, and set connection.[[CurrentRemoteDescription]] to connection.[[PendingRemoteDescription]]. Set both connection.[[PendingRemoteDescription]] and connection.[[PendingLocalDescription]] toRTCSessionDescriptionnull. Set both connection.[[LastCreatedOffer]] and connection.[[LastCreatedAnswer]] to"", set connection's signaling state to "", and release early candidates. Finally, if none of the ICE credentials in connection.[[LocalIceCredentialsToReplace]] are present in description, then set connection.[[LocalIceCredentialsToReplace]] to an empty set.stable -
If description is of type "
", then set connection.[[PendingLocalDescription]] to a newpranswerobject constructed from description, set connection's signaling state to "RTCSessionDescription", and release early candidates.have-local-pranswer
-
-
Otherwise, (if remote is
true) run one of the following steps:-
If description is of type "
", set connection.[[PendingRemoteDescription]] attribute to a newofferobject constructed from description, and set connection's signaling state to "RTCSessionDescription".have-remote-offer -
If description is of type "
", then this completes an offer answer negotiation. Set connection.[[CurrentRemoteDescription]] to a newanswerobject constructed from description, and set connection.[[CurrentLocalDescription]] to connection.[[PendingLocalDescription]]. Set both connection.[[PendingRemoteDescription]] and connection.[[PendingLocalDescription]] toRTCSessionDescriptionnull. Set both connection.[[LastCreatedOffer]] and connection.[[LastCreatedAnswer]] to"", and set connection's signaling state to "". Finally, if none of the ICE credentials in connection.[[LocalIceCredentialsToReplace]] are present in the newly set connection.[[CurrentLocalDescription]], then set connection.[[LocalIceCredentialsToReplace]] to an empty set.stable -
If description is of type "
", then set connection.[[PendingRemoteDescription]] to a newpranswerobject constructed from description and set connection's signaling state to "RTCSessionDescription".have-remote-pranswer
-
-
If description is of type "
", and it initiates the closure of an existing SCTP association, as defined in [RFC8841], Sections 10.3 and 10.4, set the value of connection.[[SctpTransport]] toanswernull. -
Let trackEventInits, muteTracks, addList, removeList and errorList be empty lists.
-
If description is of type "
" or "answer", then run the following steps:pranswer-
If description initiates the establishment of a new SCTP association, as defined in [RFC8841], Sections 10.3 and 10.4, create an RTCSctpTransport with an initial state of "
" and assign the result to the [[SctpTransport]] slot. Otherwise, if an SCTP association is established, but theconnectingmax-message-sizeSDP attribute is updated, update the data max message size of connection.[[SctpTransport]]. -
If description negotiates the DTLS role of the SCTP transport, then for each
, channel, with aRTCDataChannelnull, run the following step:id- Give channel a new ID generated
according to [RFC8832]. If no
available ID could be generated, set
channel.[[ReadyState]] to
"
", and add channnel to errorList.closed
- Give channel a new ID generated
according to [RFC8832]. If no
available ID could be generated, set
channel.[[ReadyState]] to
"
-
-
If description is not of type "
", then run the following steps:rollback-
If remote is
false, then run the following steps for each media description in description:-
If the media description was not yet associated with an
object then run the following steps:RTCRtpTransceiver-
Let transceiver be the
used to create the media description.RTCRtpTransceiver -
Set transceiver.[[Mid]] to transceiver.[[JsepMid]].
-
If transceiver.[[Stopped]] is
true, abort these sub steps. -
If the media description is indicated as using an existing media transport according to [RFC8843], let transport be the
object representing the RTP/RTCP component of that transport.RTCDtlsTransport -
Otherwise, let transport be a newly created
object with a new underlyingRTCDtlsTransport.RTCIceTransport -
Set transceiver.[[Sender]].[[SenderTransport]] to transport.
-
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.
-
-
Let transceiver be the
associated with the media description.RTCRtpTransceiver -
If transceiver.[[Stopped]] is
true, abort these sub steps. -
Let direction be an
value representing the direction from the media description.RTCRtpTransceiverDirection -
If direction is "
" or "sendrecv", set transceiver.[[Receptive]] torecvonlytrue, otherwise set it tofalse. -
Set transceiver.[[Receiver]].[[ReceiveCodecs]] to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.
-
If description is of type "
" or "answer", then run the following steps:pranswer-
Set transceiver.[[Sender]].[[SendCodecs]] to the codecs that description negotiates for sending and which the user agent is currently capable of sending, and set transceiver.[[Sender]].[[LastReturnedParameters]] to
null. -
If direction is "
" or "sendonly", and transceiver.[[FiredDirection]] is either "inactive" or "sendrecv", then run the following steps:recvonly-
Set the associated remote streams given transceiver.[[Receiver]], an empty list, another empty list, and removeList.
-
process the removal of a remote track for the media description, given transceiver and muteTracks.
-
-
Set transceiver.[[CurrentDirection]] and transceiver.[[FiredDirection]] to direction.
-
-
-
Otherwise, (if remote is
true) run the following steps for each media description in description:-
If the description is of type "
" and contains a request to receive simulcast, use the order of the rid values specified in the simulcast attribute to create anofferdictionary for each of the simulcast layers, populating theRTCRtpEncodingParametersmember according to the corresponding rid value, and let sendEncodings be the list containing the created dictionaries. Otherwise, let sendEncodings be an empty list.rid - Let supportedEncodings be the maximum number of encodings that the implementation can support. If the length of sendEncodings is greater than supportedEncodings, truncate sendEncodings so that its length is supportedEncodings.
- If sendEncodings is non-empty, set
each encoding's
toscaleResolutionDownBy2^(length of sendEncodings - encoding index - 1). -
As described by [RFC8829] (section 5.10.), attempt to find an existing
object, transceiver, to represent the media description.RTCRtpTransceiver -
If a suitable transceiver was found (transceiver is set) and sendEncodings is non-empty, set transceiver.[[Sender]].[[SendEncodings]] to sendEncodings, and set transceiver.[[Sender]].[[LastReturnedParameters]] to
null. -
If no suitable transceiver was found (transceiver is unset), run the following steps:
-
Create an RTCRtpSender, sender, from the media description using sendEncodings.
-
Create an RTCRtpReceiver, receiver, from the media description.
-
Create an RTCRtpTransceiver with sender, receiver and an
value of "RTCRtpTransceiverDirection", and let transceiver be the result.recvonly -
Add transceiver to the connection's set of transceivers.
-
-
If description is of type "
" or "answer", and transceiver. [[Sender]].[[SendEncodings]] .length is greater thanpranswer1, then run the following steps:-
If description indicates that simulcast is not supported or desired, then remove all dictionaries in transceiver.[[Sender]].[[SendEncodings]] except the first one and abort these sub steps.
-
If description rejects any of the offered layers, then remove the dictionaries that correspond to rejected layers from transceiver.[[Sender]].[[SendEncodings]].
-
Update the paused status as indicated by [RFC8853] of each simulcast layer by setting the
member on the corresponding dictionaries in transceiver.[[Sender]].[[SendEncodings]] toactivetruefor unpaused or tofalsefor paused.
-
-
Set transceiver.[[Mid]] to transceiver.[[JsepMid]].
-
Let direction be an
value representing the direction from the media description, but with the send and receive directions reversed to represent this peer's point of view. If the media description is rejected, set direction to "RTCRtpTransceiverDirection".inactive -
If direction is "
" or "sendrecv", let msids be a list of the MSIDs that the media description indicates transceiver.[[Receiver]].[[ReceiverTrack]] is to be associated with. Otherwise, let msids be an empty list.recvonlyNotemsids will be an empty list here if media description is rejected. -
Process remote tracks with transceiver, direction, msids, addList, removeList, and trackEventInits.
-
Set transceiver.[[Receiver]].[[ReceiveCodecs]] to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.
-
If description is of type "
" or "answer", then run the following steps:pranswer-
Set transceiver.[[Sender]].[[SendCodecs]] to the codecs that description negotiates for sending and which the user agent is currently capable of sending.
-
Set transceiver.[[CurrentDirection]] and transceiver.[[Direction]]s to direction.
-
Let transport be the
object representing the RTP/RTCP component of the media transport used by transceiver's associated media description, according to [RFC8843].RTCDtlsTransport -
Set transceiver.[[Sender]].[[SenderTransport]] to transport.
-
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.
-
Set the [[IceRole]] of transport according to the rules of [RFC8445].
NoteThe rules of [RFC8445] that apply here are:- If [[IceRole]] is not
, do not modify [[IceRole]].unknown - If description is a
local offer, set it to
.controlling - If description is a
remote offer, and contains
a=ice-lite, set [[IceRole]] to.controlling - If description is a
remote offer, and does not contain
a=ice-lite, set [[IceRole]] to.controlled
- If [[IceRole]] is not
-
-
If the media description is rejected, and transceiver.[[Stopped]] is
false, then stop the RTCRtpTransceiver transceiver.
-
-
-
Otherwise, (if description is of type "
") run the following steps:rollback-
Let pendingDescription be either connection.[[PendingLocalDescription]] or connection.[[PendingRemoteDescription]], whichever one is not
null. -
For each transceiver in the connection's set of transceivers run the following steps:
-
If transceiver was not associated with a media description prior to pendingDescription being set, disassociate it and set both transceiver.[[JsepMid]] and transceiver.[[Mid]] to
null. -
Set transceiver.[[Sender]].[[SenderTransport]] to transceiver.[[Sender]].[[LastStableStateSenderTransport]].
-
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transceiver.[[Receiver]].[[LastStableStateReceiverTransport]].
-
Set transceiver.[[Receiver]].[[ReceiveCodecs]] to transceiver.[[Receiver]].[[LastStableStateReceiveCodecs]].
-
If the signaling state of connection is "
", run the following sub steps:have-remote-offer-
Let msids be a list of the
ids of allMediaStreamobjects in transceiver.[[Receiver]].[[LastStableStateAssociatedRemoteMediaStreams]], or an empty list if there are none. -
Process remote tracks with transceiver, transceiver.[[CurrentDirection]], msids, addList, removeList, and trackEventInits.
-
-
If transceiver was created when pendingDescription was set, and a track has never been attached to it via
addTrack(), then stop the RTCRtpTransceiver transceiver, and remove it from connection's set of transceivers.
-
-
Set connection.[[PendingLocalDescription]] and connection.[[PendingRemoteDescription]] to
null, and set connection's signaling state to "".stable
-
-
If description is of type "
", then run the following steps:answer-
For each transceiver in the connection's set of transceivers run the following steps:
-
If transceiver is
stopped, associated with an m= section and the associated m= section is rejected in connection.[[CurrentLocalDescription]] or connection.[[CurrentRemoteDescription]], remove the transceiver from the connection's set of transceivers.
-
-
-
If connection's signaling state is now "
", run the following steps:stable-
For any transceiver that was removed from the set of transceivers in a previous step, if any of its transports (transceiver.[[Sender]].[[SenderTransport]] or transceiver.[[Receiver]].[[ReceiverTransport]]) are still not closed and they're no longer referenced by a non-stopped transceiver, close the
s and their associatedRTCDtlsTransports. This results in events firing on these objects in a queued task.RTCIceTransport -
Clear the negotiation-needed flag and update the negotiation-needed flag.
-
-
If connection's signaling state changed above, fire an event named
at connection.signalingstatechange -
For each channel in errorList, fire an event named
using theerrorinterface with theRTCErrorEventattribute set to "errorDetail" at channel.data-channel-failure -
For each track in muteTracks, set the muted state of track to the value
true. -
For each stream and track pair in removeList, remove the track track from stream.
-
For each stream and track pair in addList, add the track track to stream.
-
For each entry entry in trackEventInits, fire an event named
using thetrackinterface with itsRTCTrackEventattribute initialized to entry.receiver, itsreceiverattribute initialized to entry.track, itstrackattribute initialized to entry.streamsand itsstreamsattribute initialized to entry.transceiverat the connection object.transceiver -
Resolve p with
undefined.
-
-
-
Return p.
4.4.1.6 Set the configuration
To set a configuration, run the following steps:
-
Let configuration be the
dictionary to be processed.RTCConfiguration -
Let connection be the target
object.RTCPeerConnection -
If configuration.
is set, run the following steps:certificates-
If the length of configuration.
is different from the length of connection.[[Configuration]].certificates, throw ancertificatesInvalidModificationError. -
Let index be initialized to 0.
-
Let size be initialized to the length of configuration.
.certificates -
While index is less than size, run the following steps:
-
If the ECMAScript object represented by the value of configuration.
at index is not the same as the ECMAScript object represented by the value of connection.[[Configuration]].certificatesat index, throw ancertificatesInvalidModificationError. -
Increment index by 1.
-
-
-
If the value of configuration.
is set and its value differs from the connection's bundle policy, throw anbundlePolicyInvalidModificationError. -
If the value of configuration.
is set and its value differs from the connection's rtcpMux policy, throw anrtcpMuxPolicyInvalidModificationError. -
If the value of configuration.
is set and its value differs from the connection's previously seticeCandidatePoolSize, andiceCandidatePoolSizehas already been called, throw ansetLocalDescriptionInvalidModificationError. -
Set the ICE Agent's ICE transports setting to the value of configuration.
. As defined in [RFC8829] (section 4.1.18.), if the new ICE transports setting changes the existing setting, no action will be taken until the next gathering phase. If a script wants this to happen immediately, it should do an ICE restart.iceTransportPolicy -
Set the ICE Agent's prefetched ICE candidate pool size as defined in [RFC8829] (section 3.5.4. and section 4.1.1.) to the value of configuration.
. If the new ICE candidate pool size changes the existing setting, this may result in immediate gathering of new pooled candidates, or discarding of existing pooled candidates, as defined in [RFC8829] (section 4.1.18.).iceCandidatePoolSize -
Let validatedServers be an empty list.
-
If configuration.
is defined, then run the following steps for each element:iceServers-
Let server be the current list element.
-
Let urls be server.
.urls -
If urls is a string, set urls to a list consisting of just that string.
-
If urls is empty, throw a
SyntaxError. -
For each url in urls run the following steps:
-
Parse the url using the generic URI syntax defined in [RFC3986] and obtain the scheme name. If the parsing based on the syntax defined in [RFC3986] fails, throw a
SyntaxError. If the scheme name is not implemented by the browser throw aNotSupportedError. If scheme name isturnorturns, and parsing the url using the syntax defined in [RFC7065] fails, throw aSyntaxError. If scheme name isstunorstuns, and parsing the url using the syntax defined in [RFC7064] fails, throw aSyntaxError. -
If scheme name is
turnorturns, and either of server.or server.usernameare omitted, then throw ancredentialInvalidAccessError. -
If scheme name is
turnorturns, and server.is "credentialType", and server.passwordis not a DOMString, then throw ancredentialInvalidAccessError.
-
-
Append server to validatedServers.
-
-
Set the ICE Agent's ICE servers list to validatedServers.
As defined in [RFC8829] (section 4.1.18.), if a new list of servers replaces the ICE Agent's existing ICE servers list, no action will be taken until the next gathering phase. If a script wants this to happen immediately, it should do an ICE restart. However, if the ICE candidate pool has a nonzero size, any existing pooled candidates will be discarded, and new candidates will be gathered from the new servers.
-
Store configuration in the [[Configuration]] internal slot.
4.4.2 Interface Definition
The RTCPeerConnection interface presented in this
section is extended by several partial interfaces throughout this
specification. Notably, the RTP Media API section, which adds
the APIs to send and receive MediaStreamTrack objects.
WebIDL[Exposed=Window] 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 attribute boolean?canTrickleIceCandidates; undefinedrestartIce();RTCConfigurationgetConfiguration(); undefinedsetConfiguration(optionalRTCConfigurationconfiguration = {}); undefinedclose(); attribute EventHandleronnegotiationneeded; attribute EventHandleronicecandidate; attribute EventHandleronicecandidateerror; attribute EventHandleronsignalingstatechange; attribute EventHandleroniceconnectionstatechange; attribute EventHandleronicegatheringstatechange; attribute EventHandleronconnectionstatechange; // 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, VoidFunction successCallback,RTCPeerConnectionErrorCallbackfailureCallback); Promise<undefined>createAnswer(RTCSessionDescriptionCallbacksuccessCallback,RTCPeerConnectionErrorCallbackfailureCallback); Promise<undefined>setRemoteDescription(RTCSessionDescriptionInitdescription, VoidFunction successCallback,RTCPeerConnectionErrorCallbackfailureCallback); Promise<undefined>addIceCandidate(RTCIceCandidateInitcandidate, VoidFunction successCallback,RTCPeerConnectionErrorCallbackfailureCallback); };
Attributes
-
localDescriptionof type, readonly, nullableRTCSessionDescription -
The
attribute MUST return [[PendingLocalDescription]] if it is notlocalDescriptionnulland otherwise it MUST return [[CurrentLocalDescription]].Note that [[CurrentLocalDescription]].
and [[PendingLocalDescription]].sdpneed not be string-wise identical to thesdpvalue passed to the correspondingsdpcall (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).setLocalDescription -
currentLocalDescriptionof type, readonly, nullableRTCSessionDescription -
The
attribute MUST return [[CurrentLocalDescription]].currentLocalDescriptionIt represents the local description that was successfully negotiated the last time the
transitioned into the stable state plus any local candidates that have been generated by the ICE Agent since the offer or answer was created.RTCPeerConnection -
pendingLocalDescriptionof type, readonly, nullableRTCSessionDescription -
The
attribute MUST return [[PendingLocalDescription]].pendingLocalDescriptionIt represents a local description that is in the process of being negotiated plus any local candidates that have been generated by the ICE Agent since the offer or answer was created. If the
is in the stable state, the value isRTCPeerConnectionnull. -
remoteDescriptionof type, readonly, nullableRTCSessionDescription -
The
attribute MUST return [[PendingRemoteDescription]] if it is notremoteDescriptionnulland otherwise it MUST return [[CurrentRemoteDescription]].Note that [[CurrentRemoteDescription]].
and [[PendingRemoteDescription]].sdpneed not be string-wise identical to thesdpvalue passed to the correspondingsdpcall (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).setRemoteDescription -
currentRemoteDescriptionof type, readonly, nullableRTCSessionDescription -
The
attribute MUST return [[CurrentRemoteDescription]].currentRemoteDescriptionIt represents the last remote description that was successfully negotiated the last time the
transitioned into the stable state plus any remote candidates that have been supplied viaRTCPeerConnectionaddIceCandidate()since the offer or answer was created. -
pendingRemoteDescriptionof type, readonly, nullableRTCSessionDescription -
The
attribute MUST return [[PendingRemoteDescription]].pendingRemoteDescriptionIt represents a remote description that is in the process of being negotiated, complete with any remote candidates that have been supplied via
addIceCandidate()since the offer or answer was created. If theis in the stable state, the value isRTCPeerConnectionnull. -
signalingStateof type, readonlyRTCSignalingState -
The
attribute MUST return thesignalingStateobject's signaling state.RTCPeerConnection -
iceGatheringStateof type, readonlyRTCIceGatheringState -
The
attribute MUST return the ICE gathering state of theiceGatheringStateinstance.RTCPeerConnection -
iceConnectionStateof type, readonlyRTCIceConnectionState -
The
attribute MUST return the ICE connection state of theiceConnectionStateinstance.RTCPeerConnection -
connectionStateof type, readonlyRTCPeerConnectionState -
The
attribute MUST return the connection state of theconnectionStateinstance.RTCPeerConnection -
canTrickleIceCandidatesof type boolean, readonly, nullable -
The
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 [RFC8829] (section 4.1.17.). Prior to the completion ofcanTrickleIceCandidates, this value issetRemoteDescriptionnull. -
onnegotiationneededof type EventHandler -
The event type of this event handler is
.negotiationneeded -
onicecandidateof type EventHandler -
The event type of this event handler is
.icecandidate -
onicecandidateerrorof type EventHandler -
The event type of this event handler is
.icecandidateerror -
onsignalingstatechangeof type EventHandler -
The event type of this event handler is
.signalingstatechange -
oniceconnectionstatechangeof type EventHandler -
The event type of this event handler is
iceconnectionstatechange -
onicegatheringstatechangeof type EventHandler -
The event type of this event handler is
.icegatheringstatechange -
onconnectionstatechangeof type EventHandler -
The event type of this event handler is
.connectionstatechange
Methods
-
createOffer -
The
method generates a blob of SDP that contains an RFC 3264 offer with the supported configurations for the session, including descriptions of the localcreateOfferMediaStreamTracks attached to this, the codec/RTP/RTCP capabilities supported by this implementation, and parameters of the ICE agent and the DTLS connection. The options parameter may be supplied to provide additional control over the offer generated.RTCPeerConnectionIf a system has limited resources (e.g. a finite number of decoders),
needs to return an offer that reflects the current state of the system, so thatcreateOfferwill succeed when it attempts to acquire those resources. The session descriptions MUST remain usable bysetLocalDescriptionwithout causing an error until at least the end of the fulfillment callback of the returned promise.setLocalDescriptionCreating the SDP MUST follow the appropriate process for generating an offer described in [RFC8829], except the user agent MUST treat a
stoppingtransceiver asstoppedfor the purposes of RFC8829 in this case.As an offer, the generated SDP will contain the full set of codec/RTP/RTCP capabilities supported or preferred by the session (as opposed to an answer, which will include only a specific negotiated subset to use). In the event
is called after the session is established,createOfferwill 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.createOfferThe generated SDP will also contain the ICE agent's
,usernameFragmentand ICE options (as defined in [RFC5245], Section 14) and may also contain any local candidates that have been gathered by the agent.passwordThe
value in configuration for thecertificatesprovides 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.RTCPeerConnectionThe 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.

When the method is called, the user agent MUST run the following steps:
-
Let connection be the
object on which the method was invoked.RTCPeerConnection -
If connection.[[IsClosed]] is
true, return a promise rejected with a newly createdInvalidStateError. -
Return the result of chaining the result of creating an offer with connection to connection's operations chain.
To create an offer given connection run the following steps:
-
If connection's signaling state is neither "
" nor "stable", return a promise rejected with a newly createdhave-local-offerInvalidStateError. -
Let p be a new promise.
-
In parallel, begin the in-parallel steps to create an offer given connection and p.
-
Return p.
The in-parallel steps to create an offer given connection and a promise p are as follows:
-
If connection was not constructed with a set of certificates, and one has not yet been generated, wait for it to be generated.
-
Inspect the offerer's system state to determine the currently available resources as necessary for generating the offer, as described in [RFC8829] (section 4.1.8.).
-
If this inspection failed for any reason, reject p with a newly created
OperationErrorand abort these steps. -
Queue a task that runs the final steps to create an offer given connection and p.
The final steps to create an offer given connection and a promise p are as follows:
-
If connection.[[IsClosed]] is
true, then abort these steps. -
If connection was modified in such a way that additional inspection of the offerer's system state is necessary, then in parallel begin the in-parallel steps to create an offer again, given connection and p, and abort these steps.
NoteThis may be necessary if, for example,was called when only an audiocreateOfferwas added to connection, but while performing the in-parallel steps to create an offer, a videoRTCRtpTransceiverwas added, requiring additional inspection of video system resources.RTCRtpTransceiver -
Given the information that was obtained from previous inspection, the current state of connection and its
s, generate an SDP offer, sdpString, as described in [RFC8829] (section 5.2.).RTCRtpTransceiver-
As described in [RFC8843] (Section 7), if bundling is used (see
) an offerer tagged m= section must be selected in order to negotiate a BUNDLE group. The user agent MUST choose the m= section that corresponds to the first non-stopped transceiver in the set of transceivers as the offerer tagged m= section. This allows the remote endpoint to predict which transceiver is the offerer tagged m= section without having to parse the SDP.RTCBundlePolicy -
The codec preferences of a media description's associated transceiver is said to be the value of the
.[[PreferredCodecs]] with the following filtering applied (or said not to be set if [[PreferredCodecs]] is empty):RTCRtpTransceiver-
If the
is "direction", exclude any codecs not included in the intersection ofsendrecv.RTCRtpSender(kind).getCapabilitiesandcodecs.RTCRtpReceiver(kind).getCapabilities.codecs -
If the
is "direction", exclude any codecs not included insendonly.RTCRtpSender(kind).getCapabilities.codecs -
If the
is "direction", exclude any codecs not included inrecvonly.RTCRtpReceiver(kind).getCapabilities.codecs
The filtering MUST NOT change the order of the codec preferences.
-
-
If the length of the [[SendEncodings]] slot of the
is larger than 1, then for each encoding given in [[SendEncodings]] of theRTCRtpSender, add anRTCRtpSendera=rid sendline to the corresponding media section, and add ana=simulcast:sendline giving the RIDs in the same order as given in thefield. No RID restrictions are set.encodingsNote[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.
-
-
Let offer be a newly created
dictionary with itsRTCSessionDescriptionInitmember initialized to the string "type" and itsoffermember initialized to sdpString.sdp -
Set the [[LastCreatedOffer]] internal slot to sdpString.
-
Resolve p with offer.
-
-
createAnswer -
The
method generates an [SDP] answer with the supported configuration for the session that is compatible with the parameters in the remote configuration. LikecreateAnswer, the returned blob of SDP contains descriptions of the localcreateOfferMediaStreamTracks attached to this, the codec/RTP/RTCP options negotiated for this session, and any candidates that have been gathered by the ICE Agent. The options parameter may be supplied to provide additional control over the generated answer.RTCPeerConnectionLike
, the returned description SHOULD reflect the current state of the system. The session descriptions MUST remain usable bycreateOfferwithout causing an error until at least the end of the fulfillment callback of the returned promise.setLocalDescriptionAs an answer, the generated SDP will contain a specific codec/RTP/RTCP configuration that, along with the corresponding offer, specifies how the media plane should be established. The generation of the SDP MUST follow the appropriate process for generating an answer described in [RFC8829].
The generated SDP will also contain the ICE agent's
,usernameFragmentand ICE options (as defined in [RFC5245], Section 14) and may also contain any local candidates that have been gathered by the agent.passwordThe
value in configuration for thecertificatesprovides 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.RTCPeerConnectionAn answer can be marked as provisional, as described in [RFC8829] (section 4.1.10.1.), by setting the
to "type".pranswerWhen the method is called, the user agent MUST run the following steps:
-
Let connection be the
object on which the method was invoked.RTCPeerConnection -
If connection.[[IsClosed]] is
true, return a promise rejected with a newly createdInvalidStateError. -
Return the result of chaining the result of creating an answer with connection to connection's operations chain.
To create an answer given connection run the following steps:
-
If connection's signaling state is neither "
" nor "have-remote-offer", return a promise rejected with a newly createdhave-local-pranswerInvalidStateError. -
Let p be a new promise.
-
In parallel, begin the in-parallel steps to create an answer given connection and p.
-
Return p.
The in-parallel steps to create an answer given connection and a promise p are as follows:
-
If connection was not constructed with a set of certificates, and one has not yet been generated, wait for it to be generated.
-
Inspect the answerer's system state to determine the currently available resources as necessary for generating the answer, as described in [RFC8829] (section 4.1.9.).
-
If this inspection failed for any reason, reject p with a newly created
OperationErrorand abort these steps. -
Queue a task that runs the final steps to create an answer given p.
The final steps to create an answer given a promise p are as follows:
-
If connection.[[IsClosed]] is
true, then abort these steps. -
If connection was modified in such a way that additional inspection of the answerer's system state is necessary, then in parallel begin the in-parallel steps to create an answer again given connection and p, and abort these steps.
NoteThis may be necessary if, for example,was called when ancreateAnswer's direction was "RTCRtpTransceiver", but while performing the in-parallel steps to create an answer, the direction was changed to "recvonly", requiring additional inspection of video encoding resources.sendrecv -
Given the information that was obtained from previous inspection and the current state of connection and its
s, generate an SDP answer, sdpString, as described in [RFC8829] (section 5.3.).RTCRtpTransceiver-
The codec preferences of an m= section's associated transceiver is said to be the value of the
.[[PreferredCodecs]] with the following filtering applied (or said not to be set if [[PreferredCodecs]] is empty):RTCRtpTransceiver-
If the
is "direction", exclude any codecs not included in the intersection ofsendrecv.RTCRtpSender(kind).getCapabilitiesandcodecs.RTCRtpReceiver(kind).getCapabilities.codecs -
If the
is "direction", exclude any codecs not included insendonly.RTCRtpSender(kind).getCapabilities.codecs -
If the
is "direction", exclude any codecs not included inrecvonly.RTCRtpReceiver(kind).getCapabilities.codecs
The filtering MUST NOT change the order of the codec preferences.
-
-
If the length of the [[SendEncodings]] slot of the
is larger than 1, then for each encoding given in [[SendEncodings]] of theRTCRtpSender, add anRTCRtpSendera=rid sendline to the corresponding media section, and add ana=simulcast:sendline giving the RIDs in the same order as given in thefield. No RID restrictions are set.encodings
-
-
Let answer be a newly created
dictionary with itsRTCSessionDescriptionInitmember initialized to the string "type" and itsanswermember initialized to sdpString.sdp -
Set the [[LastCreatedAnswer]] internal slot to sdpString.
-
Resolve p with answer.
-
-
setLocalDescription -
The
method instructs thesetLocalDescriptionto apply the suppliedRTCPeerConnectionas the local description.RTCLocalSessionDescriptionInitThis API changes the local media state. In order to successfully handle scenarios where the application wants to offer to change from one media format to a different, incompatible format, the
MUST be able to simultaneously support use of both the current and pending local descriptions (e.g. support codecs that exist in both descriptions) until a final answer is received, at which point theRTCPeerConnectioncan fully adopt the pending local description, or rollback to the current description if the remote side rejected the change.RTCPeerConnectionPassing in a description is optional. If left out, then
will implicitly create an offer or create an answer, as needed. As noted in [RFC8829] (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 eithersetLocalDescriptionorcreateOffer.createAnswerWhen the method is invoked, the user agent MUST run the following steps:
-
Let description be the method's first argument.
-
Let connection be the
object on which the method was invoked.RTCPeerConnection -
Let sdp be description.
.sdp -
Return the result of chaining the following steps to connection's operations chain:
-
Let type be description.
if present, or "type" if not present and connection's signaling state is either "offer", "stable", or "have-local-offer"; otherwise "have-remote-pranswer".answer -
If type is "
", and sdp is not the empty string and not equal to connection.[[LastCreatedOffer]], then return a promise rejected with a newly createdofferInvalidModificationErrorand abort these steps. -
If type is "
" or "answer", and sdp is not the empty string and not equal to connection.[[LastCreatedAnswer]], then return a promise rejected with a newly createdpranswerInvalidModificationErrorand abort these steps. -
If sdp is the empty string, and type is "
", then run the following sub steps:offer-
Set sdp to the value of connection.[[LastCreatedOffer]].
-
If sdp is the empty string, or if it no longer accurately represents the offerer's system state of connection, then let p be the result of creating an offer with connection, and return the result of reacting to p with a fulfillment step that sets the local session description indicated by its first argument.
-
-
If sdp is the empty string, and type is "
" or "answer", then run the following sub steps:pranswer-
Set sdp to the value of connection.[[LastCreatedAnswer]].
-
If sdp is the empty string, or if it no longer accurately represents the answerer's system state of connection, then let p be the result of creating an answer with connection, and return the result of reacting to p with the following fulfillment steps:
-
Let answer be the first argument to these fulfillment steps.
-
Return the result of setting the local session description indicated by
{type, answer..}sdp
-
-
-
Return the result of setting the local session description indicated by
{type, sdp}.
-
NoteAs noted in [RFC8829] (section 5.9.), calling this method may trigger the ICE candidate gathering process by the ICE Agent.
-
-
setRemoteDescription -
The
method instructs thesetRemoteDescriptionto apply the suppliedRTCPeerConnectionas the remote offer or answer. This API changes the local media state.RTCSessionDescriptionInitWhen the method is invoked, the user agent MUST run the following steps:
-
Let description be the method's first argument.
-
Let connection be the
object on which the method was invoked.RTCPeerConnection -
Return the result of chaining the following steps to connection's operations chain:
-
If description.
is "type" and is invalid for the current signaling state of connection as described in [RFC8829] (section 5.5. and section 5.6.), then run the following sub steps:offer-
Let p be the result of setting the local session description indicated by
{type: "."}rollback -
Return the result of reacting to p with a fulfillment step that sets the remote session description description, and abort these steps.
-
-
Return the result of setting the remote session description description.
-
-
-
addIceCandidate -
The
method provides a remote candidate to the ICE Agent. This method can also be used to indicate the end of remote candidates when called with an empty string for theaddIceCandidatemember. The only members of the argument used by this method arecandidate,candidate,sdpMid, andsdpMLineIndex; the rest are ignored. When the method is invoked, the user agent MUST run the following steps:usernameFragment-
Let candidate be the method's argument.
-
Let connection be the
object on which the method was invoked.RTCPeerConnection -
If candidate.
is not an empty string and both candidate.candidateand candidate.sdpMidaresdpMLineIndexnull, return a promise rejected with a newly createdTypeError. -
Return the result of chaining the following steps to connection's operations chain:
-
If
isremoteDescriptionnullreturn a promise rejected with a newly createdInvalidStateError. -
If candidate.
is notsdpMidnull, run the following steps:-
If candidate.
is not equal to the mid of any media description insdpMid, return a promise rejected with a newly createdremoteDescriptionOperationError.
-
-
Else, if candidate.
is notsdpMLineIndexnull, run the following steps:-
If candidate.
is equal to or larger than the number of media descriptions insdpMLineIndex, return a promise rejected with a newly createdremoteDescriptionOperationError.
-
-
If either candidate.
or candidate.sdpMidindicate a media description insdpMLineIndexwhose associated transceiver isremoteDescriptionstopped, return a promise resolved withundefined. -
If candidate.
is notusernameFragmentnull, and is not equal to any username fragment present in the corresponding media description of an applied remote description, return a promise rejected with a newly createdOperationError. -
Let p be a new promise.
-
In parallel, if the candidate is not administratively prohibited, add the ICE candidate candidate as described in [RFC8829] (section 4.1.19.). Use candidate.
to identify the ICE generation; ifusernameFragmentisusernameFragmentnull, process the candidate for the most recent ICE generation.If candidate.
is an empty string, process candidate as an end-of-candidates indication for the corresponding media description and ICE candidate generation. If both candidate.candidateand candidate.sdpMidaresdpMLineIndexnull, then this end-of-candidates indication applies to all media descriptions.-
If candidate could not be successfully added the user agent MUST queue a task that runs the following steps:
-
If connection.[[IsClosed]] is
true, then abort these steps. -
Reject p with a newly created
OperationErrorand abort these steps.
-
-
If candidate is applied successfully, or if the candidate was administratively prohibited the user agent MUST queue a task that runs the following steps:
-
If connection.[[IsClosed]] is
true, then abort these steps. -
If connection.[[PendingRemoteDescription]] is not
null, and represents the ICE generation for which candidate was processed, add candidate to connection.[[PendingRemoteDescription]].sdp. -
If connection.[[CurrentRemoteDescription]] is not
null, and represents the ICE generation for which candidate was processed, add candidate to connection.[[CurrentRemoteDescription]].sdp. -
Resolve p with
undefined.
-
-
-
Return p.
-
A candidate is administratively prohibited if the UA has decided not to allow connection attempts to this address.
For privacy reasons, there is no indication to the developer about whether or not an address/port is blocked; it behaves exactly as if there was no response from the address.
The UA MUST prohibit connections to addresses on the [Fetch] block bad port list, and MAY choose to prohibit connections to other addresses.
If the
member of theiceTransportPolicyisRTCConfiguration, candidates requiring external resolution, such as mDNS candidates and DNS candidates, MUST be prohibited.relayNoteDue to WebIDL processing,
(addIceCandidatenull) is interpreted as a call with the default dictionary present, which, in the above algorithm, indicates end-of-candidates for all media descriptions and ICE candidate generation. This is by design for legacy reasons. -
-
restartIce -
The
method tells therestartIcethat ICE should be restarted. Subsequent calls toRTCPeerConnectionwill create descriptions that will restart ICE, as described in section 9.1.1.1 of [RFC5245].createOfferWhen this method is invoked, the user agent MUST run the following steps:
-
Let connection be the
on which the method was invoked.RTCPeerConnection -
Empty connection.[[LocalIceCredentialsToReplace]], and populate it with all ICE credentials (ice-ufrag and ice-pwd as defined in section 15.4 of [RFC5245]) found in connection.[[CurrentLocalDescription]], as well as all ICE credentials found in connection.[[PendingLocalDescription]].
-
Update the negotiation-needed flag for connection.
-
-
getConfiguration -
Returns an
object representing the current configuration of thisRTCConfigurationobject.RTCPeerConnectionWhen this method is called, the user agent MUST return the
object stored in the [[Configuration]] internal slot.RTCConfiguration -
setConfiguration -
The
method updates the configuration of thissetConfigurationobject. This includes changing the configuration of the ICE Agent. As noted in [RFC8829] (section 3.5.1.), when the ICE configuration changes in a way that requires a new gathering phase, an ICE restart is required.RTCPeerConnectionWhen the
method is invoked, the user agent MUST run the following steps:setConfiguration-
Let connection be the
on which the method was invoked.RTCPeerConnection -
If connection.[[IsClosed]] is
true, throw anInvalidStateError. -
Set the configuration specified by configuration.
-
-
close -
When the
method is invoked, the user agent MUST run the following steps:close-
Let connection be the
object on which the method was invoked.RTCPeerConnection - close the connection with
connection and the value
false.
The close the connection algorithm given a connection and a disappear boolean, is as follows:
-
If connection.[[IsClosed]] is
true, abort these steps. -
Set connection.[[IsClosed]] to
true. -
Set connection's signaling state to "
". This does not fire any event.closed -
Let transceivers be the result of executing the
CollectTransceiversalgorithm. For everytransceiver in transceivers, run the following steps:RTCRtpTransceiver-
If transceiver.[[Stopped]] is
true, abort these sub steps. -
Stop the RTCRtpTransceiver with transceiver and disappear.
-
-
Set the [[ReadyState]] slot of each of connection's
s to "RTCDataChannel".closedNoteThes will be closed abruptly and the closing procedure will not be invoked.RTCDataChannel -
If connection.[[SctpTransport]] is not
null, tear down the underlying SCTP association by sending an SCTP ABORT chunk and set the [[SctpTransportState]] to "".closed -
Set the [[DtlsTransportState]] slot of each of connection's
s to "RTCDtlsTransport".closed -
Destroy connection's ICE Agent, abruptly ending any active ICE processing and releasing any relevant resources (e.g. TURN permissions).
-
Set the [[IceTransportState]] slot of each of connection's
s to "RTCIceTransport".closed -
Set connection's ICE connection state to "
". This does not fire any event.closed -
Set connection's connection state to "
". This does not fire any event.closed
-
4.4.3 Legacy Interface Extensions
RTCPeerConnection interface since overloaded
functions are not allowed to be defined in partial interfaces.
Supporting the methods in this section is optional. However, if these methods are supported it is mandatory to implement according to what is specified here.
addStream method that used to exist on
RTCPeerConnection is easy to polyfill as:
RTCPeerConnection.prototype.addStream = function(stream) {
stream.getTracks().forEach((track) => this.addTrack(track, stream));
};
4.4.3.1 Method extensions
Methods
-
createOffer -
When the
createOffermethod is called, the user agent MUST run the following steps:-
Let successCallback be the method's first argument.
-
Let failureCallback be the callback indicated by the method's second argument.
-
Let options be the callback indicated by the method's third argument.
-
Run the steps specified by
'sRTCPeerConnectioncreateOffer()method with options as the sole argument, and let p be the resulting promise. -
Upon fulfillment of p with value offer, invoke successCallback with offer as the argument.
-
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
-
Return a promise resolved with
undefined.
-
-
setLocalDescription -
When the
setLocalDescriptionmethod is called, the user agent MUST run the following steps:-
Let description be the method's first argument.
-
Let successCallback be the callback indicated by the method's second argument.
-
Let failureCallback be the callback indicated by the method's third argument.
-
Run the steps specified by
'sRTCPeerConnectionmethod with description as the sole argument, and let p be the resulting promise.setLocalDescription -
Upon fulfillment of p, invoke successCallback with
undefinedas the argument. -
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
-
Return a promise resolved with
undefined.
-
-
createAnswer -
NoteThe legacy
createAnswermethod does not take anparameter, since no known legacyRTCAnswerOptionscreateAnswerimplementation ever supported it.When the
createAnswermethod is called, the user agent MUST run the following steps:-
Let successCallback be the method's first argument.
-
Let failureCallback be the callback indicated by the method's second argument.
-
Run the steps specified by
'sRTCPeerConnectioncreateAnswer()method with no arguments, and let p be the resulting promise. -
Upon fulfillment of p with value answer, invoke successCallback with answer as the argument.
-
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
-
Return a promise resolved with
undefined.
-
-
setRemoteDescription -
When the
setRemoteDescriptionmethod is called, the user agent MUST run the following steps:-
Let description be the method's first argument.
-
Let successCallback be the callback indicated by the method's second argument.
-
Let failureCallback be the callback indicated by the method's third argument.
-
Run the steps specified by
'sRTCPeerConnectionmethod with description as the sole argument, and let p be the resulting promise.setRemoteDescription -
Upon fulfillment of p, invoke successCallback with
undefinedas the argument. -
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
-
Return a promise resolved with
undefined.
-
-
addIceCandidate -
When the
addIceCandidatemethod is called, the user agent MUST run the following steps:-
Let candidate be the method's first argument.
-
Let successCallback be the callback indicated by the method's second argument.
-
Let failureCallback be the callback indicated by the method's third argument.
-
Run the steps specified by
'sRTCPeerConnectionaddIceCandidate()method with candidate as the sole argument, and let p be the resulting promise. -
Upon fulfillment of p, invoke successCallback with
undefinedas the argument. -
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
-
Return a promise resolved with
undefined.
-
Callback Definitions
These callbacks are only used on the legacy APIs.
RTCPeerConnectionErrorCallback
WebIDLcallback RTCPeerConnectionErrorCallback = undefined (DOMException error);
Callback RTCPeerConnectionErrorCallback Parameters
RTCPeerConnectionErrorCallback-
errorof typeDOMException - An error object encapsulating information about what went wrong.
RTCSessionDescriptionCallback
WebIDLcallbackRTCSessionDescriptionCallback= undefined (RTCSessionDescriptionInitdescription);
Callback RTCSessionDescriptionCallback Parameters
RTCSessionDescriptionCallback-
description of type
RTCSessionDescriptionInit - The object containing the SDP [SDP].
4.4.3.2 Legacy configuration extensions
This section describes a set of legacy extensions that may be
used to influence how an offer is created, in addition to the
media added to the . Developers are
encouraged to use the RTCPeerConnection API instead.
RTCRtpTransceiver
When is called with any of the
legacy options specified in this section, run the followings
steps instead of the regular createOffer
steps:
createOffer
-
Let options be the methods first argument.
-
Let connection be the current
object.RTCPeerConnection -
For each
offerToReceive<Kind>member in options with kind, kind, run the following steps:- If the value of the dictionary member is false,
-
For each non-stopped "
" transceiver of transceiver kind kind, set transceiver.[[Direction]] to "sendrecv".sendonly -
For each non-stopped "
" transceiver of transceiver kind kind, set transceiver.[[Direction]] to "recvonly".inactive
Continue with the next option, if any.
-
-
If connection has any non-stopped "
" or "sendrecv" transceivers of transceiver kind kind, continue with the next option, if any.recvonly -
Let transceiver be the result of invoking the equivalent of connection.
(kind), except that this operation MUST NOT update the negotiation-needed flag.addTransceiver -
If transceiver is unset because the previous operation threw an error, abort these steps.
-
Set transceiver.[[Direction]] to "
".recvonly
- If the value of the dictionary member is false,
-
Run the steps specified by
to create the offer.createOffer
WebIDLpartial dictionaryRTCOfferOptions{ booleanofferToReceiveAudio; booleanofferToReceiveVideo; };
Attributes
-
offerToReceiveAudioof type boolean -
This setting provides additional control over the directionality of audio. For example, it can be used to ensure that audio can be received, regardless if audio is sent or not.
-
offerToReceiveVideoof type boolean -
This setting provides additional control over the directionality of video. For example, it can be used to ensure that video can be received, regardless if video is sent or not.
4.4.4 Garbage collection
An object MUST not be garbage collected as
long as any event can cause an event handler to be triggered on the
object. When the object's [[IsClosed]] internal slot is
RTCPeerConnectiontrue, no such event handler can be triggered and it is
therefore safe to garbage collect the object.
All and RTCDataChannelMediaStreamTrack objects that are
connected to an have a strong reference to
the RTCPeerConnection object.
RTCPeerConnection
4.5 Error Handling
4.5.1 General Principles
All methods that return promises are governed by the standard error handling rules of promises. Methods that do not return promises may throw exceptions to indicate errors.
4.6 Session Description Model
4.6.1
RTCSdpType
The enum describes the type of an
RTCSdpType, RTCSessionDescriptionInit,
or RTCLocalSessionDescriptionInit instance.
RTCSessionDescription
WebIDLenumRTCSdpType{ "offer", "pranswer", "answer", "rollback" };
| Enumeration description | |
|---|---|
offer
|
An |
pranswer
|
An |
answer
|
An |
rollback
|
An |
4.6.2
RTCSessionDescription Class
The class is used by
RTCSessionDescription to expose local and remote session
descriptions.
RTCPeerConnection
WebIDL[Exposed=Window] interfaceRTCSessionDescription{constructor(RTCSessionDescriptionInitdescriptionInitDict); readonly attributeRTCSdpTypetype; readonly attribute DOMStringsdp; [Default] objecttoJSON(); };
Constructors
-
constructor() -
The
RTCSessionDescription()constructor takes a dictionary argument, description, whose content is used to initialize the newobject. This constructor is deprecated; it exists for legacy compatibility reasons only.RTCSessionDescription
Attributes
-
typeof type, readonlyRTCSdpType - The type of this session description.
-
sdpof type DOMString, readonly, defaulting to"" - The string representation of the SDP [SDP].
Methods
-
toJSON() - When called, run [WEBIDL]'s default toJSON steps.
WebIDLdictionaryRTCSessionDescriptionInit{ requiredRTCSdpTypetype; DOMStringsdp= ""; };
Dictionary RTCSessionDescriptionInit Members
-
typeof type, requiredRTCSdpType - The type of this session description.
-
sdpof type DOMString -
The string representation of the SDP [SDP]; if
is "type", this member is unused.rollback
WebIDLdictionaryRTCLocalSessionDescriptionInit{RTCSdpTypetype; DOMStringsdp= ""; };
Dictionary RTCLocalSessionDescriptionInit Members
-
typeof typeRTCSdpType -
The type of this description. If not present, then
will infer the type based on thesetLocalDescription's signaling state.RTCPeerConnection -
sdpof type DOMString -
The string representation of the SDP [SDP]; if
is "type", this member is unused.rollback
4.7 Session Negotiation Model
Many changes to state of an will require
communication with the remote side via the signaling channel, in
order to have the desired effect. The app can be kept informed as to
when it needs to do signaling, by listening to the RTCPeerConnectionnegotiationneeded event. This event is fired according
to the state of the connection's negotiation-needed flag,
represented by a [[NegotiationNeeded]] internal slot.
4.7.1 Setting Negotiation-Needed
This section is non-normative.
If an operation is performed on an that
requires signaling, the connection will be marked as needing
negotiation. Examples of such operations include adding or stopping
an RTCPeerConnection, or adding the first RTCRtpTransceiver.
RTCDataChannel
Internal changes within the implementation can also result in the connection being marked as needing negotiation.
Note that the exact procedures for updating the negotiation-needed flag are specified below.
4.7.2 Clearing Negotiation-Needed
This section is non-normative.
The negotiation-needed flag is cleared when a session description
of type "" is
set successfully, and the supplied description
matches the state of the answers and
RTCRtpTransceivers that currently exist on the
RTCDataChannel. Specifically, this means that all
non-RTCPeerConnectionstopped transceivers have an associated section in the local description with matching
properties, and, if any data channels have been created, a data
section exists in the local description.
Note that the exact procedures for updating the negotiation-needed flag are specified below.
4.7.3 Updating the Negotiation-Needed flag
The process below occurs where referenced elsewhere in this document. It also may occur as a result of internal changes within the implementation that affect negotiation. If such changes occur, the user agent MUST update the negotiation-needed flag.
To update the negotiation-needed flag for connection, run the following steps:
-
If the length of connection.[[Operations]] is not
0, then set connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] totrue, and abort these steps. -
Queue a task to run the following steps:
-
If connection.[[IsClosed]] is
true, abort these steps. -
If the length of connection.[[Operations]] is not
0, then set connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] totrue, and abort these steps. -
If connection's signaling state is not "
", abort these steps.stableNoteThe negotiation-needed flag will be updated once the state transitions to "
", as part of the steps for setting a session description.stable -
If the result of checking if negotiation is needed is
false, clear the negotiation-needed flag by setting connection.[[NegotiationNeeded]] tofalse, and abort these steps. -
If connection.[[NegotiationNeeded]] is already
true, abort these steps. -
Set connection.[[NegotiationNeeded]] to
true. -
Fire an event named
at connection.negotiationneeded
NoteThe task queueing prevents
from firing prematurely, in the common situation where multiple modifications to connection are being made at once.negotiationneededAdditionally, we avoid racing with negotiation methods by only firing
when the operations chain is empty.negotiationneeded -
To check if negotiation is needed for connection, perform the following checks:
-
If any implementation-specific negotiation is required, as described at the start of this section, return
true. -
If connection.[[LocalIceCredentialsToReplace]] is not empty, return
true. -
Let description be connection.[[CurrentLocalDescription]].
-
If connection has created any
s, and no m= section in description has been negotiated yet for data, returnRTCDataChanneltrue. -
For each transceiver in connection's set of transceivers, perform the following checks:
-
If transceiver.[[Stopping]] is
trueand transceiver.[[Stopped]] isfalse, returntrue. -
If transceiver isn't
stoppedand isn't yet associated with an m= section in description, returntrue. -
If transceiver isn't
stoppedand is associated with an m= section in description then perform the following checks:-
If transceiver.[[Direction]] is "
" or "sendrecv", and the associated m= section in description either doesn't contain a singlesendonlya=msidline, or the number of MSIDs from thea=msidlines in thism=section, or the MSID values themselves, differ from what is in transceiver.sender.[[AssociatedMediaStreamIds]], returntrue. -
If description is of type "
", and the direction of the associated m= section in neither connection.[[CurrentLocalDescription]] nor connection.[[CurrentRemoteDescription]] matches transceiver.[[Direction]], returnoffertrue. 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. -
If description is of type "
", and the direction of the associated m= section in the description does not match transceiver.[[Direction]] intersected with the offered direction (as described in [RFC8829] (section 5.3.1.)), returnanswertrue.
-
-
If transceiver is
stoppedand is associated with an m= section, but the associated m= section is not yet rejected in connection.[[CurrentLocalDescription]] or connection.[[CurrentRemoteDescription]], returntrue.
-
-
If all the preceding checks were performed and
truewas not returned, nothing remains to be negotiated; returnfalse.
4.8 Interfaces for Interactive Connectivity Establishment
4.8.1
RTCIceCandidate Interface
This interface describes an ICE candidate, described in [RFC5245]
Section 2. Other than ,
candidate,
sdpMid, and
sdpMLineIndex, the remaining attributes
are derived from parsing the usernameFragment
member in candidateInitDict, if it is well formed.
candidate
WebIDL[Exposed=Window] interfaceRTCIceCandidate{constructor(optionalRTCIceCandidateInitcandidateInitDict = {}); readonly attribute DOMStringcandidate; readonly attribute DOMString?sdpMid; readonly attribute unsigned short?sdpMLineIndex; readonly attribute DOMString?foundation; readonly attributeRTCIceComponent?component; readonly attribute unsigned long?priority; readonly attribute DOMString?address; readonly attributeRTCIceProtocol?protocol; readonly attribute unsigned short?port; readonly attributeRTCIceCandidateType?type; readonly attributeRTCIceTcpCandidateType?tcpType; readonly attribute DOMString?usernameFragment;RTCIceCandidateInittoJSON(); };
Constructor
-
constructor() -
The
RTCIceCandidate()constructor takes a dictionary argument, candidateInitDict, whose content is used to initialize the newobject.RTCIceCandidateWhen invoked, run the following steps:
- If both
the
andsdpMidmembers of candidateInitDict aresdpMLineIndexnull, throw aTypeError. -
Return the result of creating an RTCIceCandidate with candidateInitDict.
To create an RTCIceCandidate with a candidateInitDict dictionary, run the following steps:
- Let iceCandidate be a newly created
object.RTCIceCandidate - Create internal slots for the following attributes of
iceCandidate, initilized to
null:,foundation,component,priority,address,protocol,port,type,tcpType, andrelatedAddress.relatedPort - Create internal slots for the following attributes of
iceCandidate, initilized to their namesakes in
candidateInitDict:
,candidate,sdpMid,sdpMLineIndex.usernameFragment - Let candidate be the
dictionary member of candidateInitDict. If candidate is not an empty string, run the following steps:candidate- Parse candidate using the
candidate-attributegrammar. - If parsing of
candidate-attributehas failed, abort these steps. - If any field in the parse result represents an invalid value for the corresponding attribute in iceCandidate, abort these steps.
- Set the corresponding internal slots in iceCandidate to the field values of the parsed result.
- Parse candidate using the
- Return iceCandidate.
NoteThe constructor for
only does basic parsing and type checking for the dictionary members in candidateInitDict. Detailed validation on the well-formedness ofRTCIceCandidate,candidate,sdpMid,sdpMLineIndexwith the corresponding session description is done when passing theusernameFragmentobject toRTCIceCandidateaddIceCandidate().To maintain backward compatibility, any error on parsing the candidate attribute is ignored. In such case, the
attribute holds the rawcandidatestring given in candidateInitDict, but derivative attributes such ascandidate,foundation, etc are set toprioritynull. - If both
the
Attributes
Most attributes below are defined in section 15.1 of [RFC5245].
-
candidateof type DOMString, readonly -
This carries the
candidate-attributeas defined in section 15.1 of [RFC5245]. If thisrepresents an end-of-candidates indication or a peer reflexive remote candidate,RTCIceCandidateis an empty string.candidate -
sdpMidof type DOMString, readonly, nullable -
If not
null, this contains the media stream "identification-tag" defined in [RFC5888] for the media component this candidate is associated with. -
sdpMLineIndexof type unsigned short, readonly, nullable -
If not
null, this indicates the index (starting at zero) of the media description in the SDP this candidate is associated with. -
foundationof type DOMString, readonly, nullable -
A unique identifier that allows ICE to correlate candidates
that appear on multiple
s.RTCIceTransport -
componentof type, readonly, nullableRTCIceComponent -
The assigned network component of the candidate
("
" or "rtp"). This corresponds to thertcpcomponent-idfield incandidate-attribute, decoded to the string representation as defined in.RTCIceComponent -
priorityof type unsigned long, readonly, nullable - The assigned priority of the candidate.
-
addressof type DOMString, readonly, nullable -
The address of the candidate, allowing for IPv4 addresses, IPv6 addresses, and fully qualified domain names (FQDNs). This corresponds to the
connection-addressfield incandidate-attribute.Remote candidates may be exposed, for instance via [[SelectedCandidatePair]].
. By default, the user agent MUST leave theremoteattribute asaddressnullfor any exposed remote candidate. Once ainstance learns on an address by the web application usingRTCPeerConnection, the user agent can expose theaddIceCandidateattribute value in anyaddressof theRTCIceCandidateinstance representing a remote candidate with that newly learnt address.RTCPeerConnectionNoteThe addresses exposed in candidates gathered via ICE and made visibile to the application in
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.RTCIceCandidateThese 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.

Applications can avoid exposing addresses to the communicating party, either temporarily or permanently, by forcing the ICE Agent to report only relay candidates via the
member oficeTransportPolicy.RTCConfigurationTo limit the addresses exposed to the application itself, browsers can offer their users different policies regarding sharing local addresses, as defined in [RFC8828].
-
protocolof type, readonly, nullableRTCIceProtocol -
The protocol of the candidate
("
"/"udp"). This corresponds to thetcptransportfield incandidate-attribute. -
portof type unsigned short, readonly, nullable - The port of the candidate.
-
typeof type, readonly, nullableRTCIceCandidateType -
The type of the candidate. This corresponds to the
candidate-typesfield incandidate-attribute. -
tcpTypeof type, readonly, nullableRTCIceTcpCandidateType -
If
is "protocol",tcprepresents the type of TCP candidate. Otherwise,tcpTypeistcpTypenull. This corresponds to thetcp-typefield incandidate-attribute. -
relatedAddressof type DOMString, readonly, nullable -
For a candidate that is derived from another, such as a relay
or reflexive candidate, the
is the IP address of the candidate that it is derived from. For host candidates, therelatedAddressisrelatedAddressnull. This corresponds to therel-addressfield incandidate-attribute. -
relatedPortof type unsigned short, readonly, nullable -
For a candidate that is derived from another, such as a relay
or reflexive candidate, the
is the port of the candidate that it is derived from. For host candidates, therelatedPortisrelatedPortnull. This corresponds to therel-portfield incandidate-attribute. -
usernameFragmentof type DOMString, readonly, nullable -
This carries the
ufragas defined in section 15.4 of [RFC5245].
Methods
-
toJSON() -
To invoke the
toJSON()operation of theinterface, run the following steps:RTCIceCandidate- Let json be a new
dictionary.RTCIceCandidateInit - For each attribute identifier
attr in «
,candidate,sdpMid,sdpMLineIndex»:usernameFragment- Let value be the result of getting the
underlying value of the attribute identified by
attr, given this
object.RTCIceCandidate - Set
json[attr]to value.
- Let value be the result of getting the
underlying value of the attribute identified by
attr, given this
- Return json.
- Let json be a new
WebIDLdictionaryRTCIceCandidateInit{ DOMStringcandidate= ""; DOMString?sdpMid= null; unsigned short?sdpMLineIndex= null; DOMString?usernameFragment= null; };
Dictionary RTCIceCandidateInit Members
-
candidateof type DOMString, defaulting to"" -
This carries the
candidate-attributeas defined in section 15.1 of [RFC5245]. If this represents an end-of-candidates indication,is an empty string.candidate -
sdpMidof type DOMString, nullable, defaulting tonull -
If not
null, this contains the media stream "identification-tag" defined in [RFC5888] for the media component this candidate is associated with. -
sdpMLineIndexof type unsigned short, nullable, defaulting tonull -
If not
null, this indicates the index (starting at zero) of the media description in the SDP this candidate is associated with. -
usernameFragmentof type DOMString, nullable, defaulting tonull -
If not
null, this carries theufragas defined in section 15.4 of [RFC5245].
4.8.1.1
candidate-attribute Grammar
The candidate-attribute grammar is used to parse the
member of
candidateInitDict in the candidateRTCIceCandidate()
constructor.
The primary grammar for candidate-attribute is defined in
section 15.1 of [RFC5245]. In addition, the browser MUST support
the grammar extension for ICE TCP as defined in section 4.5 of
[RFC6544].
The browser MAY support other grammar extensions for candidate-attribute as defined in other RFCs.
4.8.1.2
RTCIceProtocol Enum
The represents the protocol of the ICE
candidate.
RTCIceProtocol
4.8.1.3
RTCIceTcpCandidateType Enum
The represents the type of the ICE TCP
candidate, as defined in [RFC6544].
RTCIceTcpCandidateType
WebIDLenumRTCIceTcpCandidateType{ "active", "passive", "so" };
| Enumeration description | |
|---|---|
active
|
An "" TCP candidate is
one for which the transport will attempt to open an
outbound connection but will not receive incoming
connection requests.
|
passive
|
A "" TCP candidate is
one for which the transport will receive incoming
connection attempts but not attempt a connection.
|
so
|
An "" candidate is one for
which the transport will attempt to open a connection
simultaneously with its peer.
|
The user agent will typically only gather
ICE TCP candidates.
active
4.8.1.4
RTCIceCandidateType Enum
The represents the type of the ICE
candidate, as defined in [RFC5245] section 15.1.
RTCIceCandidateType
WebIDLenumRTCIceCandidateType{ "host", "srflx", "prflx", "relay" };
| Enumeration description | |
|---|---|
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]. |
4.8.2
RTCPeerConnectionIceEvent
The icecandidate event of the
uses the RTCPeerConnection
interface.
RTCPeerConnectionIceEvent
When firing an event that contains an
RTCPeerConnectionIceEvent object, it MUST include values for both
RTCIceCandidate and sdpMid.
If the sdpMLineIndex is of type
"RTCIceCandidate" or type
"srflx", the
relay property of the event MUST be set
to the URL of the ICE server from which the candidate was obtained.
url
icecandidate event is used for three different types of
indications:
-
A candidate has been gathered. The
member of the event will be populated normally. It should be signaled to the remote peer and passed intocandidate.addIceCandidate -
An
has finished gathering a generation of candidates, and is providing an end-of-candidates indication as defined by Section 8.2 of [RFC8838]. This is indicated byRTCIceTransport.candidatebeing set to an empty string. Thecandidateobject should be signaled to the remote peer and passed intocandidatelike a typical ICE candidate, in order to provide the end-of-candidates indication to the remote peer.addIceCandidate -
All
s have finished gathering candidates, and theRTCIceTransport'sRTCPeerConnectionhas transitioned to "RTCIceGatheringState". This is indicated by thecompletemember of the event being set tocandidatenull. This only exists for backwards compatibility, and this event does not need to be signaled to the remote peer. It's equivalent to anevent with the "icegatheringstatechange" state.complete
WebIDL[Exposed=Window] interfaceRTCPeerConnectionIceEvent: Event {constructor(DOMString type, optionalRTCPeerConnectionIceEventIniteventInitDict = {}); readonly attributeRTCIceCandidate?candidate; readonly attribute DOMString?url; };
Constructors
-
RTCPeerConnectionIceEvent.constructor()
Attributes
-
candidateof type, readonly, nullableRTCIceCandidate -
The
attribute is thecandidateobject with the new ICE candidate that caused the event.RTCIceCandidateThis attribute is set to
nullwhen an event is generated to indicate the end of candidate gathering.NoteEven where there are multiple media components, only one event containing a
nullcandidate is fired. -
urlof type DOMString, readonly, nullable -
The
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 tourlnull.
WebIDL dictionaryRTCPeerConnectionIceEventInit: EventInit {RTCIceCandidate?candidate; DOMString?url; };
Dictionary RTCPeerConnectionIceEventInit Members
-
candidateof type, nullableRTCIceCandidate -
See the
attribute of thecandidateinterface.RTCPeerConnectionIceEvent -
urlof type DOMString, nullable -
The
attribute is the STUN or TURN URL that identifies the STUN or TURN server used to gather this candidate.url
4.8.3
RTCPeerConnectionIceErrorEvent
The icecandidateerror event of the
uses the RTCPeerConnection
interface.
RTCPeerConnectionIceErrorEvent
WebIDL[Exposed=Window] interfaceRTCPeerConnectionIceErrorEvent: Event {constructor(DOMString type,RTCPeerConnectionIceErrorEventIniteventInitDict); readonly attribute DOMString?address; readonly attribute unsigned short?port; readonly attribute DOMStringurl; readonly attribute unsigned shorterrorCode; readonly attribute USVStringerrorText; };
Constructors
-
RTCPeerConnectionIceErrorEvent.constructor()
Attributes
-
addressof type DOMString, readonly, nullable -
The
attribute is the local IP address used to communicate with the STUN or TURN server.addressOn a multihomed system, multiple interfaces may be used to contact the server, and this attribute allows the application to figure out on which one the failure occurred.
If the local IP address value is not already exposed as part of a local candidate, the
attribute will be set toaddressnull. -
portof type unsigned short, readonly, nullable -
The
attribute is the port used to communicate with the STUN or TURN server.portIf the
attribute isaddressnull, theattribute is also set toportnull. -
urlof type DOMString, readonly -
The
attribute is the STUN or TURN URL that identifies the STUN or TURN server for which the failure occurred.url -
errorCodeof type unsigned short, readonly -
The
attribute is the numeric STUN error code returned by the STUN or TURN server [STUN-PARAMETERS].errorCodeIf no host candidate can reach the server,
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 theerrorCodeof "RTCIceGatheringState".gathering -
errorTextof type USVString, readonly -
The
attribute is the STUN reason text returned by the STUN or TURN server [STUN-PARAMETERS].errorTextIf the server could not be reached,
will be set to an implementation-specific value providing details about the error.errorText
WebIDL dictionaryRTCPeerConnectionIceErrorEventInit: EventInit { DOMString?address; unsigned short?port; DOMStringurl; required unsigned shorterrorCode; USVStringerrorText; };
Dictionary RTCPeerConnectionIceErrorEventInit
Members
-
addressof type DOMString, nullable -
The local address used to communicate with the STUN or TURN server, or
null. -
portof type unsigned short, nullable -
The local port used to communicate with the STUN or TURN server, or
null. -
urlof type DOMString -
The STUN or TURN URL that identifies the STUN or TURN server for which the failure occurred.
-
errorCodeof type unsigned short, required -
The numeric STUN error code returned by the STUN or TURN server.
-
errorTextof type USVString -
The STUN reason text returned by the STUN or TURN server.
4.9 Certificate Management
The certificates that instances use to
authenticate with peers use the RTCPeerConnection interface. These
objects can be explicitly generated by applications using the
RTCCertificate method and can be provided
in the generateCertificate when constructing a new
RTCConfiguration instance.
RTCPeerConnection
The explicit certificate management functions provided here are
optional. If an application does not provide the
configuration option when
constructing an certificates a new set of certificates MUST
be generated by the user agent. That set MUST include an ECDSA
certificate with a private key on the P-256 curve and a signature
with a SHA-256 hash.
RTCPeerConnection
WebIDLpartial interfaceRTCPeerConnection{ static Promise<RTCCertificate>generateCertificate(AlgorithmIdentifier keygenAlgorithm); };
Methods
-
generateCertificate, static -
The
function causes the user agent to create an X.509 certificate [X509V3] and corresponding private key. A handle to information is provided in the form of thegenerateCertificateinterface. The returnedRTCCertificatecan be used to control the certificate that is offered in the DTLS sessions established byRTCCertificate.RTCPeerConnectionThe keygenAlgorithm argument is used to control how the private key associated with the certificate is generated. The keygenAlgorithm argument uses the WebCrypto [WebCryptoAPI] AlgorithmIdentifier type.
The following values MUST be supported by a user agent:
{ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, and{ name: "ECDSA", namedCurve: "P-256" }.NoteIt is expected that a user agent will have a small or even fixed set of values that it will accept.
The certificate produced by this process also contains a signature. The validity of this signature is only relevant for compatibility reasons. Only the public key and the resulting certificate fingerprint are used by
, but it is more likely that a certificate will be accepted if the certificate is well formed. The browser selects the algorithm used to sign the certificate; a browser SHOULD select SHA-256 [FIPS-180-4] if a hash algorithm is needed.RTCPeerConnectionThe resulting certificate MUST NOT include information that can be linked to a user or user agent. Randomized values for distinguished name and serial number SHOULD be used.
When the method is called, the user agent MUST run the following steps:
-
Let keygenAlgorithm be the first argument to
.generateCertificate -
Let expires be a
DOMTimeStampvalue of 2592000000.NoteThis means the certificate will by default expire in 30 days from the time of the
call.generateCertificate -
If keygenAlgorithm is an object, run the following steps:
-
Let certificateExpiration be the result of converting the ECMAScript object represented by keygenAlgorithm to an
dictionary.RTCCertificateExpiration -
If the conversion fails with an error, return a promise that is rejected with error.
-
If certificateExpiration.
is notexpiresundefined, set expires to certificateExpiration..expires -
If expires is greater than 31536000000, set expires to 31536000000.
NoteThis means the certificate cannot be valid for longer than 365 days from the time of the
call.generateCertificateA user agent MAY further cap the value of expires.
-
-
Let normalizedKeygenAlgorithm be the result of normalizing an algorithm with an operation name of
generateKeyand a supportedAlgorithms value specific to production of certificates for.RTCPeerConnection -
If the above normalization step fails with an error, return a promise that is rejected with error.
-
If the normalizedKeygenAlgorithm parameter identifies an algorithm that the user agent cannot or will not use to generate a certificate for
, return a promise that is rejected with aRTCPeerConnectionDOMExceptionof typeNotSupportedError. In particular, normalizedKeygenAlgorithm MUST be an asymmetric algorithm that can be used to produce a signature used to authenticate DTLS connections. -
Let p be a new promise.
-
Run the following steps in parallel:
-
Perform the generate key operation specified by normalizedKeygenAlgorithm using keygenAlgorithm.
-
Let generatedKeyingMaterial and generatedKeyCertificate be the private keying material and certificate generated by the above step.
-
Let certificate be a new
object.RTCCertificate -
Set certificate.[[Expires]] to the current time plus expires value.
-
Set certificate.[[Origin]] to the relevant settings object's origin.
-
Store the generatedKeyingMaterial in a secure module, and let handle be a reference identifier to it.
-
Set certificate.[[KeyingMaterialHandle]] to handle.
-
Set certificate.[[Certificate]] to generatedCertificate.
-
Resolve p with certificate.
-
-
Return p.
-
4.9.1
RTCCertificateExpiration Dictionary
is used to set an expiration date on
certificates generated by
RTCCertificateExpiration.
generateCertificate
WebIDLdictionaryRTCCertificateExpiration{ [EnforceRange] DOMTimeStampexpires; };
-
expires, of typeDOMTimeStamp -
An optional
attribute MAY be added to the definition of the algorithm that is passed toexpires. If this parameter is present it indicates the maximum time that thegenerateCertificateis valid for relative to the current time.RTCCertificate
4.9.2
RTCCertificate Interface
The interface represents a certificate used to
authenticate WebRTC communications. In addition to the visible
properties, internal slots contain a handle to the generated
private keying materal ([[KeyingMaterialHandle]]), a
certificate ([[Certificate]]) that
RTCCertificate uses to authenticate with a peer, and the
origin ([[Origin]]) that created the object.
RTCPeerConnection
WebIDL[Exposed=Window, Serializable] interfaceRTCCertificate{ readonly attribute DOMTimeStampexpires; sequence<RTCDtlsFingerprint>getFingerprints(); };
Attributes
-
expiresof type DOMTimeStamp, readonly -
The expires attribute indicates the date and time in milliseconds relative to 1970-01-01T00:00:00Z after which the certificate will be considered invalid by the browser. After this time, attempts to construct an
using this certificate fail.RTCPeerConnectionNote that this value might not be reflected in a
notAfterparameter 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. Implementations
MUST support applications storing and retrieving
objects from persistent storage, in a manner that also preserves
the keying material referenced by [[KeyingMaterialHandle]].
Implementations SHOULD store the sensitive keying material in a
secure module safe from same-process memory attacks. This allows
the private key to be stored and used, but not easily read using a
memory attack.
RTCCertificate
objects are serializable objects
[HTML]. Their serialization steps, given value
and serialized, are:
RTCCertificate
- Set serialized.[[Expires]] to the value of
value.
attribute.expires - Set serialized.[[Certificate]] to a copy of the unstructured binary data in value.[[Certificate]].
- Set serialized.[[Origin]] to a copy of the unstructured binary data in value.[[Origin]].
- Set serialized.[[KeyingMaterialHandle]] to a serialization of the handle in value.[[KeyingMaterialHandle]] (not the private keying material itself).
Their deserialization steps, given serialized and value, are:
- Initialize value.
attribute to contain serialized.[[Expires]].expires - Set value.[[Certificate]] to a copy of serialized.[[Certificate]].
- Set value.[[Origin]] to a copy of serialized.[[Origin]].
- Set value.[[KeyingMaterialHandle]] to the private keying material handle resulting from deserializing serialized.[[KeyingMaterialHandle]].
Supporting structured cloning in this manner allows
instances to be persisted to stores. It also
allows instances to be passed to other origins using APIs like
RTCCertificatepostMessage(message, options) [html]. However, the object cannot
be used by any other origin than the one that originally created
it.
5. RTP Media API
The RTP media API lets a web application send and receive
MediaStreamTracks over a peer-to-peer connection. Tracks, when
added to an , result in signaling; when this
signaling is forwarded to a remote peer, it causes corresponding tracks
to be created on the remote side.
RTCPeerConnection
There is not an exact 1:1 correspondence between tracks sent by one
and received by the other. For one, IDs of tracks
sent have no mapping to the IDs of tracks received. Also,
RTCPeerConnection changes the track sent by an
replaceTrack without creating a new track on the receiver side; the
corresponding RTCRtpSender will only have a single track,
potentially representing multiple sources of media stitched together.
Both RTCRtpReceiver and
addTransceiver can be used to cause the same track to be
sent multiple times, which will be observed on the receiver side as
multiple receivers each with its own separate track. Thus it's more
accurate to think of a 1:1 relationship between an replaceTrack on
one side and an RTCRtpSender's track on the other side, matching
senders and receivers using the RTCRtpReceiver's
RTCRtpTransceiver if necessary.
mid
When sending media, the sender may need to rescale or resample the media to meet various requirements including the envelope negotiated by SDP.
Following the rules in [RFC8829] (section 3.6.), the video MAY be downscaled in order to fit the SDP constraints. The media MUST NOT be upscaled to create fake data that did not occur in the input source, the media MUST NOT be cropped except as needed to satisfy constraints on pixel counts, and the aspect ratio MUST NOT be changed.
The WebRTC Working Group is seeking implementation feedback on the need and timeline for a more complex handling of this situation. Some possible designs have been discussed in GitHub issue 1283.
When video is rescaled, for example for certain combinations of width
or height and
values, situations when the resulting width or height is not an integer
may occur. In such situations the user agent MUST use the integer part of the
result. What to transmit if the integer part of the scaled width or
height is zero is implementation-specific.
scaleResolutionDownBy
The actual encoding and transmission of MediaStreamTracks is
managed through objects called s. Similarly, the
reception and decoding of RTCRtpSenderMediaStreamTracks is managed through
objects called s. Each RTCRtpReceiver is associated
with at most one track, and each track to be received is associated
with exactly one RTCRtpSender.
RTCRtpReceiver
The encoding and transmission of each MediaStreamTrack SHOULD be
made such that its characteristics (width,
height and frameRate
for video tracks; sampleSize, sampleRate and
channelCount for audio tracks) are to a
reasonable degree retained by the track created on the remote side.
There are situations when this does not apply, there may for example be
resource constraints at either endpoint or in the network or there may
be settings applied that instruct the implementation
to act differently.
RTCRtpSender
An object contains a set of RTCPeerConnections,
representing the paired senders and receivers with some shared state.
This set is
initialized to the empty set when the RTCRtpTransceiver object is
created. RTCPeerConnections and RTCRtpSenders are always
created at the same time as an RTCRtpReceiver, which they will
remain attached to for their lifetime. RTCRtpTransceivers are
created implicitly when the application attaches a RTCRtpTransceiverMediaStreamTrack
to an via the RTCPeerConnectionaddTrack()
method, or explicitly when the application uses the
method. They are also created when
a remote description is applied that includes a new media description.
Additionally, when a remote description is applied that indicates the
remote endpoint has media to send, the relevant addTransceiverMediaStreamTrack
and are surfaced to the application via the
RTCRtpReceiver event.
track
In order for an to send and/or receive media with
another endpoint this must be negotiated with SDP such that both
endpoints have an RTCRtpTransceiver object that is associated
with the same media description.
RTCRtpTransceiver
When creating an offer, enough media descriptions will be generated to cover all transceivers on that end. When this offer is set as the local description, any disassociated transceivers get associated with media descriptions in the offer.
When an offer is set as the remote description, any media descriptions
in it not yet associated with a transceiver get associated with a new
or existing transceiver. In this case, only disassociated transceivers
that were created via the addTrack() method may
be associated. Disassociated transceivers created via the
addTransceiver() method, however, won't get
associated even if media descriptions are available in the remote
offer. Instead, new transceivers will be created and associated if
there aren't enough addTrack()-created
transceivers. This sets addTrack()-created and
addTransceiver()-created transceivers apart in a
critical way that is not observable from inspecting their attributes.
When creating an answer, only media media descriptions that were
present in the offer may be listed in the answer. As a consequence, any
transceivers that were not associated when setting the remote offer
remain disassociated after setting the local answer. This can be
remedied by the answerer creating a follow-up offer, initiating another
offer/answer exchange, or in the case of using
addTrack()-created transceivers, making sure that
enough media descriptions are offered in the initial exchange.
5.1 RTCPeerConnection Interface Extensions
The RTP media API extends the interface as
described below.
RTCPeerConnection
WebIDL partial interfaceRTCPeerConnection{ sequence<RTCRtpSender>getSenders(); sequence<RTCRtpReceiver>getReceivers(); sequence<RTCRtpTransceiver>getTransceivers();RTCRtpSenderaddTrack(MediaStreamTrack track, MediaStream... streams); undefinedremoveTrack(RTCRtpSendersender);RTCRtpTransceiveraddTransceiver((MediaStreamTrack or DOMString) trackOrKind, optionalRTCRtpTransceiverInitinit = {}); attribute EventHandlerontrack; };
Attributes
-
ontrackof type EventHandler -
The event type of this event handler is
.track
Methods
-
getSenders -
Returns a sequence of
objects representing the RTP senders that belong to non-stoppedRTCRtpSenderobjects currently attached to thisRTCRtpTransceiverobject.RTCPeerConnectionWhen the
method is invoked, the user agent MUST return the result of executing thegetSendersCollectSendersalgorithm.We define the CollectSenders algorithm as follows:
- Let
transceivers be the result of executing the
CollectTransceiversalgorithm. - Let senders be a new empty sequence.
- For each transceiver in
transceivers,
- If
transceiver.[[Stopped]] is
false, add transceiver.[[Sender]] to senders.
- If
transceiver.[[Stopped]] is
- Return senders.
- Let
transceivers be the result of executing the
-
getReceivers -
Returns a sequence of
objects representing the RTP receivers that belong to non-stoppedRTCRtpReceiverobjects currently attached to thisRTCRtpTransceiverobject.RTCPeerConnectionWhen the
method is invoked, the user agent MUST run the following steps:getReceivers- Let
transceivers be the result of executing the
CollectTransceiversalgorithm. - Let receivers be a new empty sequence.
- For each
transceiver in transceivers,
- If transceiver.[[Stopped]] is
false, add transceiver.[[Receiver]] to receivers.
- If transceiver.[[Stopped]] is
- Return receivers.
- Let
transceivers be the result of executing the
-
getTransceivers -
Returns a sequence of
objects representing the RTP transceivers that are currently attached to thisRTCRtpTransceiverobject.RTCPeerConnectionThe
method MUST return the result of executing thegetTransceiversCollectTransceiversalgorithm.We define the CollectTransceivers algorithm as follows:
- Let
transceivers be a new sequence consisting of all
objects in thisRTCRtpTransceiverobject's set of transceivers, in insertion order.RTCPeerConnection - Return transceivers.
- Let
transceivers be a new sequence consisting of all
-
addTrack -
Adds a new track to the
, and indicates that it is contained in the specifiedRTCPeerConnectionMediaStreams.When the
method is invoked, the user agent MUST run the following steps:addTrack-
Let connection be the
object on which this method was invoked.RTCPeerConnection -
Let track be the
MediaStreamTrackobject indicated by the method's first argument. -
Let kind be track.kind.
-
Let streams be a list of
MediaStreamobjects constructed from the method's remaining arguments, or an empty list if the method was called with a single argument. -
If connection.[[IsClosed]] is
true, throw anInvalidStateError. -
Let senders be the result of executing the
CollectSendersalgorithm. If anfor track already exists in senders, throw anRTCRtpSenderInvalidAccessError. -
The steps below describe how to determine if an existing sender can be reused. Doing so will cause future calls to
andcreateOfferto mark the corresponding media description ascreateAnswersendrecvorsendonlyand add the MSID of the sender's streams, as defined in [RFC8829] (section 5.2.2. and section 5.3.2.).If any
object in senders matches all the following criteria, let sender be that object, orRTCRtpSendernullotherwise:-
The sender's track is null.
-
The transceiver kind of the
, associated with the sender, matches kind.RTCRtpTransceiver -
The [[Stopping]] slot of the
associated with the sender isRTCRtpTransceiverfalse. -
The sender has never been used to send. More precisely, the [[CurrentDirection]] slot of the
associated with the sender has never had a value of "RTCRtpTransceiver" or "sendrecv".sendonly
-
-
If sender is not
null, run the following steps to use that sender:-
Set sender.[[SenderTrack]] to track.
-
Set sender.[[AssociatedMediaStreamIds]] to an empty set.
-
For each stream in streams, add stream.id to [[AssociatedMediaStreamIds]] if it's not already there.
-
Let transceiver be the
associated with sender.RTCRtpTransceiver -
If transceiver.[[Direction]] is "
", set transceiver.[[Direction]] to "recvonly".sendrecv -
If transceiver.[[Direction]] is "
", set transceiver.[[Direction]] to "inactive".sendonly
-
-
If sender is
null, run the following steps:-
Create an RTCRtpSender with track, kind and streams, and let sender be the result.
-
Create an RTCRtpReceiver with kind, and let receiver be the result.
-
Create an RTCRtpTransceiver with sender, receiver and an
value of "RTCRtpTransceiverDirection", and let transceiver be the result.sendrecv -
Add transceiver to connection's set of transceivers.
-
-
A track could have contents that are inaccessible to the application. This can be due to anything that would make a track CORS cross-origin. These tracks can be supplied to the
addTrack()method, and have ancreated for them, but content MUST NOT be transmitted. Silence (audio), black frames (video) or equivalently absent content is sent in place of track content.RTCRtpSenderNote that this property can change over time.
-
Update the negotiation-needed flag for connection.
-
Return sender.
-
-
removeTrack -
Stops sending media from sender. The
will still appear inRTCRtpSender. Doing so will cause future calls togetSendersto mark the media description for the corresponding transceiver as "createOffer" or "recvonly", as defined in [RFC8829] (section 5.2.2.).inactiveWhen the other peer stops sending a track in this manner, the track is removed from any remote
MediaStreams that were initially revealed in thetrackevent, and if theMediaStreamTrackis not already muted, amuteevent is fired at the track.NoteThe same effect asremoveTrack()can be achieved by setting the.RTCRtpTransceiverattribute of the corresponding transceiver and invokingdirection.RTCRtpSender(null) on the sender. One minor difference is thatreplaceTrackreplaceTrack()is asynchronous andremoveTrack()is synchronous.When the
method is invoked, the user agent MUST run the following steps:removeTrack-
Let sender be the argument to
.removeTrack -
Let connection be the
object on which the method was invoked.RTCPeerConnection -
If connection.[[IsClosed]] is
true, throw anInvalidStateError. -
If sender was not created by connection, throw an
InvalidAccessError. -
Let senders be the result of executing the
CollectSendersalgorithm. -
If sender is not in senders (which indicates its transceiver was stopped or removed due to setting a session description of
"type"), then abort these steps.rollback -
If sender.[[SenderTrack]] is null, abort these steps.
-
Set sender.[[SenderTrack]] to null.
-
Let transceiver be the
object corresponding to sender.RTCRtpTransceiver -
If transceiver.[[Direction]] is "
", set transceiver.[[Direction]] to "sendrecv".recvonly -
If transceiver.[[Direction]] is "
", set transceiver.[[Direction]] to "sendonly".inactive -
Update the negotiation-needed flag for connection.
-
-
addTransceiver -
Create a new
and add it to the set of transceivers.RTCRtpTransceiverAdding a transceiver will cause future calls to
to add a media description for the corresponding transceiver, as defined in [RFC8829] (section 5.2.2.).createOfferThe initial value of
is null. Setting a session description may later change it to a non-null value.midThe
argument can be used to specify the number of offered simulcast encodings, and optionally their RIDs and encoding parameters.sendEncodingsWhen this method is invoked, the user agent MUST run the following steps:
-
Let init be the second argument.
-
Let streams be init.
.streams -
Let sendEncodings be init.
.sendEncodings -
Let direction be init.
.direction -
If the first argument is a string, let it be kind and run the following steps:
-
If kind is not a legal
MediaStreamTrackkind, throw aTypeError. -
Let track be
null.
-
-
If the first argument is a
MediaStreamTrack, let it be track and let kind be track.kind. -
If connection.[[IsClosed]] is
true, throw anInvalidStateError. - Validate sendEncodings by running the
following steps:
-
Verify that each
value in sendEncodings conforms to the grammar specified in Section 10 of [RFC8851]. If one of the RIDs does not meet these requirements, throw aridTypeError. -
If any
dictionary in sendEncodings contains a read-only parameter other thanRTCRtpEncodingParameters, throw anridInvalidAccessError. -
Verify that the value of each
member in sendEncodings that is defined is greater than or equal to 1.0. If one of thescaleResolutionDownByvalues does not meet this requirement, throw ascaleResolutionDownByRangeError. -
Let maxN be the maximum number of total simultaneous encodings the user agent may support for this kind, at minimum
1.This should be an optimistic number since the codec to be used is not known yet. -
If sendEncodings contains any encoding whose
attribute is defined, set any undefinedscaleResolutionDownByof the other encodings to 1.0.scaleResolutionDownBy -
If the number of
stored in sendEncodings exceeds maxN, then trim sendEncodings from the tail until its length is maxN.RTCRtpEncodingParameters - If the
attribues of sendEncodings are still undefined, initialize each encoding'sscaleResolutionDownBytoscaleResolutionDownBy2^(length of sendEncodings - encoding index - 1). This results in smaller-to-larger resolutions where the last encoding has no scaling applied to it, e.g. 4:2:1 if the length is 3. -
If the number of
now stored in sendEncodings isRTCRtpEncodingParameters1, then remove anymember from the lone entry.ridNoteProviding a single, defaultin sendEncodings allows the application to subsequently set encoding parameters usingRTCRtpEncodingParameters, even when simulcast isn't used.setParameters
-
-
Create an RTCRtpSender with track, kind, streams and sendEncodings and let sender be the result.
If sendEncodings is set, then subsequent calls to
will be configured to send multiple RTP encodings as defined in [RFC8829] (section 5.2.2. and section 5.2.1.). WhencreateOfferis called with a corresponding remote description that is able to receive multiple RTP encodings as defined in [RFC8829] (section 3.7.), thesetRemoteDescriptionmay send multiple RTP encodings and the parameters retrieved via the transceiver'sRTCRtpSender.sendergetParameters()will reflect the encodings negotiated. -
Create an RTCRtpReceiver with kind and let receiver be the result.
-
Create an RTCRtpTransceiver with sender, receiver and direction, and let transceiver be the result.
-
Add transceiver to connection's set of transceivers.
-
Update the negotiation-needed flag for connection.
-
Return transceiver.
-
WebIDLdictionaryRTCRtpTransceiverInit{RTCRtpTransceiverDirectiondirection= "sendrecv"; sequence<MediaStream>streams= []; sequence<RTCRtpEncodingParameters>sendEncodings= []; };
Dictionary RTCRtpTransceiverInit Members
-
directionof type, defaulting to "RTCRtpTransceiverDirection"sendrecv -
The direction of the
.RTCRtpTransceiver -
streamsof type sequence<MediaStream> -
When the remote PeerConnection's track event fires corresponding to the
being added, these are the streams that will be put in the event.RTCRtpReceiver -
sendEncodingsof type sequence<>RTCRtpEncodingParameters -
A sequence containing parameters for sending RTP encodings of media.
WebIDLenumRTCRtpTransceiverDirection{ "sendrecv", "sendonly", "recvonly", "inactive", "stopped" };
RTCRtpTransceiverDirection Enumeration description
|
|
|---|---|
sendrecv
|
The 's
sender will offer to send RTP, and will send RTP
if the remote peer accepts and
sender.().[i].
is true for any value of i. The
's will offer to
receive RTP, and will receive RTP if the remote peer accepts.
|
sendonly
|
The 's
sender will offer to send RTP, and will send RTP
if the remote peer accepts and
sender.().[i].
is true for any value of i. The
's will not offer to
receive RTP, and will not receive RTP.
|
recvonly
|
The 's will not offer
to send RTP, and will not send RTP. The
's will offer to
receive RTP, and will receive RTP if the remote peer accepts.
|
inactive
|
The 's will not offer
to send RTP, and will not send RTP. The
's will not offer to
receive RTP, and will not receive RTP.
|
stopped
|
The will neither send nor receive RTP.
It will generate a zero port in the offer. In answers, its
will not offer to send RTP, and its
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
"" to turn off both
directions temporarily, or to
"inactive" to reject only the
incoming side. To permanently reject an m-line in a manner that
makes it available for reuse, the application would need to call
sendonly.RTCRtpTransceiverstop() and subsequently
initiate negotiation from its end.
To process remote tracks
given an transceiver,
direction, msids, addList,
removeList, and trackEventInits, run the
following steps:
RTCRtpTransceiver
-
Set the associated remote streams with transceiver.[[Receiver]], msids, addList, and removeList.
-
If direction is "
" or "sendrecv" and transceiver.[[FiredDirection]] is neither "recvonly" nor "sendrecv", or the previous step increased the length of addList, process the addition of a remote track with transceiver and trackEventInits.recvonly -
If direction is "
" or "sendonly", set transceiver.[[Receptive]] toinactivefalse. -
If direction is "
" or "sendonly", and transceiver.[[FiredDirection]] is either "inactive" or "sendrecv", process the removal of a remote track for the media description, with transceiver and muteTracks.recvonly -
Set transceiver.[[FiredDirection]] to direction.
To process the addition of
a remote track given an
transceiver and trackEventInits, run the
following steps:
RTCRtpTransceiver
-
Let receiver be transceiver.[[Receiver]].
-
Let track be receiver.[[ReceiverTrack]].
-
Let streams be receiver.[[AssociatedRemoteMediaStreams]].
-
Create a new
dictionary with receiver, track, streams and transceiver as members and add it to trackEventInits.RTCTrackEventInit
To process the removal of a
remote track with an
transceiver and muteTracks, run the following
steps:
RTCRtpTransceiver
-
Let receiver be transceiver.[[Receiver]].
-
Let track be receiver.[[ReceiverTrack]].
-
If track.muted is
false, add track to muteTracks.
To set the associated
remote streams given receiver,
msids, addList, and removeList,
run the following steps:
RTCRtpReceiver
-
Let connection be the
object associated with receiver.RTCPeerConnection -
For each MSID in msids, unless a
MediaStreamobject has previously been created with thatidfor this connection, create aMediaStreamobject with thatid. -
Let streams be a list of the
MediaStreamobjects created for this connection with theids corresponding to msids. -
Let track be receiver.[[ReceiverTrack]].
-
For each stream in receiver.[[AssociatedRemoteMediaStreams]] that is not present in streams, add stream and track as a pair to removeList.
-
For each stream in streams that is not present in receiver.[[AssociatedRemoteMediaStreams]], add stream and track as a pair to addList.
-
Set receiver.[[AssociatedRemoteMediaStreams]] to streams.
5.2
RTCRtpSender Interface
The interface allows an application to control how a
given RTCRtpSenderMediaStreamTrack is encoded and transmitted to a remote
peer. When is called on an
setParameters object, the encoding is changed appropriately.
RTCRtpSender
To create an RTCRtpSender with a MediaStreamTrack,
track, a string, kind, a list of
MediaStream objects, streams, and optionally a list of
objects, sendEncodings, run
the following steps:
RTCRtpEncodingParameters
-
Let sender be a new
object.RTCRtpSender -
Let sender have a [[SenderTrack]] internal slot initialized to track.
-
Let sender have a [[SenderTransport]] internal slot initialized to
null. -
Let sender have a [[LastStableStateSenderTransport]] internal slot initialized to
null. -
Let sender have a [[Dtmf]] internal slot initialized to
null. -
If kind is
"audio"then create an RTCDTMFSender dtmf and set the [[Dtmf]] internal slot to dtmf. -
Let sender have an [[AssociatedMediaStreamIds]] internal slot, representing a list of Ids of
MediaStreamobjects that this sender is to be associated with. The [[AssociatedMediaStreamIds]] slot is used when sender is represented in SDP as described in [RFC8829] (section 5.2.1.). -
Set sender.[[AssociatedMediaStreamIds]] to an empty set.
-
For each stream in streams, add stream.id to [[AssociatedMediaStreamIds]] if it's not already there.
-
Let sender have a [[SendEncodings]] internal slot, representing a list of
dictionaries.RTCRtpEncodingParameters -
If sendEncodings is given as input to this algorithm, and is non-empty, set the [[SendEncodings]] slot to sendEncodings. Otherwise, set it to a list containing a single
withRTCRtpEncodingParametersset toactivetrue. -
Let sender have a [[SendCodecs]] internal slot, representing a list of
dictionaries, and initialized to an empty list.RTCRtpCodecParameters -
Let sender have a [[LastReturnedParameters]] internal slot, which will be used to match
andgetParameterstransactions.setParameters -
Return sender.
WebIDL[Exposed=Window] interfaceRTCRtpSender{ readonly attribute MediaStreamTrack?track; readonly attributeRTCDtlsTransport?transport; staticRTCRtpCapabilities?getCapabilities(DOMString kind); Promise<undefined>setParameters(RTCRtpSendParametersparameters);RTCRtpSendParametersgetParameters(); Promise<undefined>replaceTrack(MediaStreamTrack? withTrack); undefinedsetStreams(MediaStream... streams); Promise<RTCStatsReport>getStats(); };
Attributes
-
trackof typeMediaStreamTrack, readonly, nullable -
The
attribute is the track that is associated with thistrackobject. IfRTCRtpSenderis ended, or if the track's output is disabled, i.e. the track is disabled and/or muted, thetrackMUST send black frames (video) and MUST NOT send (audio). In the case of video, theRTCRtpSenderSHOULD send one black frame per second. IfRTCRtpSenderistracknullthen thedoes not send. On getting, the attribute MUST return the value of the [[SenderTrack]] slot.RTCRtpSender -
transportof type, readonly, nullableRTCDtlsTransport -
The
attribute is the transport over which media fromtransportis sent in the form of RTP packets. Prior to construction of thetrackobject, theRTCDtlsTransportattribute will be null. When bundling is used, multipletransportobjects will share oneRTCRtpSenderand will all send RTP and RTCP over the same transport.transportOn getting, the attribute MUST return the value of the [[SenderTransport]] slot.
Methods
-
getCapabilities, static -
The
getCapabilities()method returns the most optimistic view of the capabilities of the system for sending media of the given kind. It does not reserve any resources, ports, or other state but is meant to provide a way to discover the types of capabilities of the browser including which codecs may be supported. User agents MUST support kind values of"audio"and"video". If the system has no capabilities corresponding to the value of the kind argument,returnsgetCapabilitiesnull.These capabilities provide generally persistent cross-origin information on the device and thus increases the fingerprinting surface of the application. In privacy-sensitive contexts, browsers can consider mitigations such as reporting only a common subset of the capabilities.
NoteThe codec capabilities returned affect the
setCodecPreferences()algorithm and what inputs it throwsInvalidModificationErroron, and should also be consistent with information revealed bycreateOffer()andcreateAnswer()about codecs negotiated for sending, to ensure any privacy mitigations are effective. -
setParameters -
The
method updates howsetParametersis encoded and transmitted to a remote peer.trackWhen the
method is called, the user agent MUST run the following steps:setParameters- Let parameters be the method's first argument.
- Let sender be the
object on whichRTCRtpSenderis invoked.setParameters - Let transceiver be the
object associated with sender (i.e. sender is transceiver.[[Sender]]).RTCRtpTransceiver -
If transceiver.[[Stopped]] is
true, return a promise rejected with a newly createdInvalidStateError. - If
sender.[[LastReturnedParameters]] is
null, return a promise rejected with a newly createdInvalidStateError. - Validate parameters by running the following
steps:
- Let encodings be
parameters.
.encodings - Let codecs be
parameters.
.codecs - Let N be the number
of
stored in sender.[[SendEncodings]].RTCRtpEncodingParameters - If any of the following conditions are met, return a
promise rejected with a newly created
InvalidModificationError:-
encodings.lengthis different from N. - encodings has been re-ordered.
- Any parameter in parameters is marked as a Read-only parameter (such as RID) and has a value that is different from the corresponding parameter value in sender.[[LastReturnedParameters]]. Note that this also applies to transactionId.
-
-
Verify that each encoding in encodings has a
member whose value is greater than or equal to 1.0. If one of thescaleResolutionDownByvalues does not meet this requirement, return a promise rejected with a newly createdscaleResolutionDownByRangeError.
- Let encodings be
parameters.
- Let p be a new promise.
- In parallel, configure the media stack to use
parameters to transmit
sender.[[SenderTrack]].
- If the media stack is successfully configured with
parameters, queue a task to run the following
steps:
-
Set
sender.[[LastReturnedParameters]]
to
null. - Set sender.[[SendEncodings]]
to
parameters.
.encodings - Resolve p with
undefined.
-
Set
sender.[[LastReturnedParameters]]
to
- If any error occurred while configuring the media
stack, queue a task to run the following steps:
- If an error occurred due to hardware resources
not being available, reject p with a
newly created
whoseRTCErroris set to "errorDetail" and abort these steps.hardware-encoder-not-available - If an error occurred due to a hardware encoder
not supporting parameters, reject
p with a newly created
whoseRTCErroris set to "errorDetail" and abort these steps.hardware-encoder-error - For all other errors, reject p
with a newly created
OperationError.
- If an error occurred due to hardware resources
not being available, reject p with a
newly created
- If the media stack is successfully configured with
parameters, queue a task to run the following
steps:
- Return p.
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 thesetParametersdictionary are designed to not enable this, so attributes likeRTCRtpSendParametersthat cannot be changed are read-only. Other things, like bitrate, are controlled using limits such ascname, 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.maxBitrate -
getParameters -
The
getParameters()method returns theobject's current parameters for howRTCRtpSenderis encoded and transmitted to a remotetrack.RTCRtpReceiverWhen
is called, the user agent MUST run the following steps:getParameters-
Let sender be the
object on which the getter was invoked.RTCRtpSender -
If sender.[[LastReturnedParameters]] is not
null, return sender.[[LastReturnedParameters]], and abort these steps. -
Let result be a new
dictionary constructed as follows:RTCRtpSendParameters-
is set to a new unique identifier.transactionId -
is set to the value of the [[SendEncodings]] internal slot.encodings -
The
sequence is populated based on the header extensions that have been negotiated for sending.headerExtensions -
is set to the value of the [[SendCodecs]] internal slot.codecs -
.rtcpis set to the CNAME of the associatedcname.RTCPeerConnection.rtcpis set toreducedSizetrueif reduced-size RTCP has been negotiated for sending, andfalseotherwise.
-
-
Set sender.[[LastReturnedParameters]] to result.
-
Queue a task that sets sender.[[LastReturnedParameters]] to
null. -
Return result.
may be used withgetParametersto change the parameters in the following way:setParametersasync function updateParameters() { 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 to
, subsequent calls tosetParameterswill return the modified set of parameters.getParameters -
-
replaceTrack -
Attempts to replace the
's currentRTCRtpSenderwith another track provided (or with atracknulltrack), without renegotiation.When the
method is invoked, the user agent MUST run the following steps:replaceTrack-
Let sender be the
object on whichRTCRtpSenderis invoked.replaceTrack -
Let transceiver be the
object associated with sender.RTCRtpTransceiver -
Let connection be the
object associated with sender.RTCPeerConnection -
Let withTrack be the argument to this method.
-
If withTrack is non-null and
withTrack.kinddiffers from the transceiver kind of transceiver, return a promise rejected with a newly createdTypeError. -
Return the result of chaining the following steps to connection's operations chain:
-
If transceiver.[[Stopped]] is
true, return a promise rejected with a newly createdInvalidStateError. -
Let p be a new promise.
-
Let sending be
trueif transceiver.[[CurrentDirection]] is "" or "sendrecv", andsendonlyfalseotherwise. -
Run the following steps in parallel:
-
If sending is
true, and withTrack isnull, have the sender stop sending. -
If sending is
true, and withTrack is notnull, determine if withTrack can be sent immediately by the sender without violating the sender's already-negotiated envelope, and if it cannot, then reject p with a newly createdInvalidModificationError, and abort these steps. -
If sending is
true, and withTrack is notnull, have the sender switch seamlessly to transmitting withTrack instead of the sender's existing track. -
Queue a task that runs the following steps:
-
If connection.[[IsClosed]] is
true, abort these steps. -
Set sender.[[SenderTrack]] to withTrack.
-
Resolve p with
undefined.
-
-
-
Return p.
-
NoteChanging dimensions and/or frame rates might not require negotiation. Cases that may require negotiation include:
- Changing a resolution to a value outside of the negotiated imageattr bounds, as described in [RFC6236].
- Changing a frame rate to a value that causes the block rate for the codec to be exceeded.
- A video track differing in raw vs. pre-encoded format.
- An audio track having a different number of channels.
- 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 the
MediaStreams to be associated with this sender's track.When the
method is invoked, the user agent MUST run the following steps:setStreams-
Let sender be the
object on which this method was invoked.RTCRtpSender -
Let connection be the
object on which this method was invoked.RTCPeerConnection -
If connection.[[IsClosed]] is
true, throw anInvalidStateError. -
Let streams be a list of
MediaStreamobjects constructed from the method's arguments, or an empty list if the method was called without arguments. -
Set sender.[[AssociatedMediaStreamIds]] to an empty set.
-
For each stream in streams, add stream.id to [[AssociatedMediaStreamIds]] if it's not already there.
-
Update the negotiation-needed flag for connection.
-
-
getStats -
Gathers stats for this sender only and reports the result asynchronously.
When the
getStats()method is invoked, the user agent MUST run the following steps:-
Let selector be the
object on which the method was invoked.RTCRtpSender -
Let p be a new promise, and run the following steps in parallel:
-
Gather the stats indicated by selector according to the stats selection algorithm.
-
Resolve p with the resulting
object, containing the gathered stats.RTCStatsReport
-
-
Return p.
-
5.2.1
RTCRtpParameters Dictionary
WebIDLdictionaryRTCRtpParameters{ required sequence<RTCRtpHeaderExtensionParameters>headerExtensions; requiredRTCRtcpParametersrtcp; required sequence<RTCRtpCodecParameters>codecs; };
Dictionary RTCRtpParameters Members
RTCRtpParameters-
headerExtensionsof type sequence<>, requiredRTCRtpHeaderExtensionParameters -
A sequence containing parameters for RTP header extensions. Read-only parameter.
-
rtcpof type, requiredRTCRtcpParameters -
Parameters used for RTCP. Read-only parameter.
-
codecsof type sequence<>, requiredRTCRtpCodecParameters -
A sequence containing the media codecs that an
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 inRTCRtpSenderwith acodecsattribute indicating retransmission viamimeTypeaudio/rtxorvideo/rtx, and anattribute (providing the "apt" and "rtx-time" parameters). Read-only parameter.sdpFmtpLine
5.2.2
RTCRtpSendParameters Dictionary
WebIDL dictionaryRTCRtpSendParameters:RTCRtpParameters{ required DOMStringtransactionId; required sequence<RTCRtpEncodingParameters>encodings; };
Dictionary RTCRtpSendParameters Members
RTCRtpSendParameters-
transactionIdof type DOMString, required -
A unique identifier for the last set of parameters applied. Ensures that
can only be called based on a previoussetParameters, and that there are no intervening changes. Read-only parameter.getParameters -
encodingsof type sequence<>, requiredRTCRtpEncodingParameters -
A sequence containing parameters for RTP encodings of media.
5.2.3
RTCRtpReceiveParameters Dictionary
WebIDL dictionaryRTCRtpReceiveParameters:RTCRtpParameters{ };
5.2.4
RTCRtpCodingParameters Dictionary
WebIDLdictionaryRTCRtpCodingParameters{ DOMStringrid; };
Dictionary RTCRtpCodingParameters Members
RTCRtpCodingParameters-
ridof type DOMString -
If set, this RTP encoding will be sent with the RID header extension as defined by [RFC8829] (section 5.2.1.). The RID is not modifiable via
. It can only be set or modified insetParameterson the sending side. Read-only parameter.addTransceiver
5.2.5
RTCRtpDecodingParameters Dictionary
WebIDLdictionaryRTCRtpDecodingParameters:RTCRtpCodingParameters{};
5.2.6
RTCRtpEncodingParameters Dictionary
WebIDL dictionaryRTCRtpEncodingParameters:RTCRtpCodingParameters{ booleanactive= true; unsigned longmaxBitrate; doublescaleResolutionDownBy; };
Dictionary RTCRtpEncodingParameters Members
RTCRtpEncodingParameters-
activeof type boolean, defaulting totrue -
Indicates that this encoding is actively being sent. Setting it to
falsecauses this encoding to no longer be sent. Setting it totruecauses this encoding to be sent. Since setting the value tofalsedoes not cause the SSRC to be removed, an RTCP BYE is not sent. -
maxBitrateof type unsigned 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 the
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.maxBitrateis 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 ofmaxBitrateis bits per second.maxBitrateNoteHow 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.
-
scaleResolutionDownByof type double -
This member is only present if the sender's
kindis"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 by a factor of two to the power of the layer's number, in 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.will be 1.0).scaleResolutionDownBy
5.2.7
RTCRtcpParameters Dictionary
WebIDLdictionaryRTCRtcpParameters{ DOMStringcname; booleanreducedSize; };
Dictionary RTCRtcpParameters Members
RTCRtcpParameters-
cnameof type DOMString -
The Canonical Name (CNAME) used by RTCP (e.g. in SDES messages). Read-only parameter.
-
reducedSizeof type boolean -
Whether reduced size RTCP [RFC5506] is configured (if true) or compound RTCP as specified in [RFC3550] (if false). Read-only parameter.
5.2.8
RTCRtpHeaderExtensionParameters Dictionary
WebIDLdictionaryRTCRtpHeaderExtensionParameters{ required DOMStringuri; required unsigned shortid; booleanencrypted= false; };
Dictionary RTCRtpHeaderExtensionParameters Members
RTCRtpHeaderExtensionParameters-
uriof type DOMString, required -
The URI of the RTP header extension, as defined in [RFC5285]. Read-only parameter.
-
idof type unsigned short, required -
The value put in the RTP packet to identify the header extension. Read-only parameter.
-
encryptedof type boolean -
Whether the header extension is encrypted or not. Read-only parameter.
The dictionary enables an
application to determine whether a header extension is configured
for use within an RTCRtpHeaderExtensionParameters or RTCRtpSender. For an
RTCRtpReceiver transceiver, an application can
determine the "direction" parameter (defined in Section 5 of
[RFC5285]) of a header extension as follows without having to
parse SDP:
RTCRtpTransceiver
- sendonly: The header extension is only included in
transceiver.
.sendergetParameters()..headerExtensions - recvonly: The header extension is only included in
transceiver.
.receivergetParameters()..headerExtensions - sendrecv: The header extension is included in both
transceiver.
.sendergetParameters().and transceiver.headerExtensions.receivergetParameters()..headerExtensions - inactive: The header extension is included in neither
transceiver.
.sendergetParameters().nor transceiver.headerExtensions.receivergetParameters()..headerExtensions
5.2.9
RTCRtpCodecParameters Dictionary
WebIDLdictionaryRTCRtpCodecParameters{ required octetpayloadType; required DOMStringmimeType; required unsigned longclockRate; unsigned shortchannels; DOMStringsdpFmtpLine; };
Dictionary RTCRtpCodecParameters Members
RTCRtpCodecParameters-
payloadTypeof type octet, required -
The RTP payload type used to identify this codec. Read-only parameter.
-
mimeTypeof type DOMString, required -
The codec MIME media type/subtype. Valid media types and subtypes are listed in [IANA-RTP-2]. Read-only parameter.
-
clockRateof type unsigned long, required -
The codec clock rate expressed in Hertz. Read-only parameter.
-
channelsof type unsigned short -
When present, indicates the number of channels (mono=1, stereo=2). Read-only parameter.
-
sdpFmtpLineof type DOMString -
The "format specific parameters" field from the
a=fmtpline in the SDP corresponding to the codec, if one exists, as defined by [RFC8829] (section 5.8.). For an, these parameters come from the remote description, and for anRTCRtpSender, they come from the local description. Read-only parameter.RTCRtpReceiver
5.2.10
RTCRtpCapabilities Dictionary
WebIDLdictionaryRTCRtpCapabilities{ required sequence<RTCRtpCodecCapability>codecs; required sequence<RTCRtpHeaderExtensionCapability>headerExtensions; };
Dictionary RTCRtpCapabilities Members
RTCRtpCapabilities-
codecsof type sequence<>, requiredRTCRtpCodecCapability -
Supported media codecs as well as entries for RTX, RED and FEC mechanisms. There will only be a single entry in
for retransmission via RTX, withcodecsnot present.sdpFmtpLine -
headerExtensionsof type sequence<>, requiredRTCRtpHeaderExtensionCapability -
Supported RTP header extensions.
5.2.11
RTCRtpCodecCapability Dictionary
WebIDLdictionaryRTCRtpCodecCapability{ required DOMStringmimeType; required unsigned longclockRate; unsigned shortchannels; DOMStringsdpFmtpLine; };
Dictionary RTCRtpCodecCapability Members
RTCRtpCodecCapability
The dictionary provides information
about codec capabilities. Only capability combinations that
would utilize distinct payload types in a generated SDP offer
are provided. For example:
RTCRtpCodecCapability
- Two H.264/AVC codecs, one for each of two supported packetization-mode values.
- Two CN codecs with different clock rates.
-
mimeTypeof type DOMString, required -
The codec MIME media type/subtype. Valid media types and subtypes are listed in [IANA-RTP-2].
-
clockRateof type unsigned long, required -
The codec clock rate expressed in Hertz.
-
channelsof type unsigned short -
If present, indicates the maximum number of channels (mono=1, stereo=2).
-
sdpFmtpLineof type DOMString -
The "format specific parameters" field from the
a=fmtpline in the SDP corresponding to the codec, if one exists.
5.2.12
RTCRtpHeaderExtensionCapability Dictionary
WebIDLdictionaryRTCRtpHeaderExtensionCapability{ DOMStringuri; };
Dictionary RTCRtpHeaderExtensionCapability Members
RTCRtpHeaderExtensionCapability-
uriof type DOMString -
The URI of the RTP header extension, as defined in [RFC5285].
5.3
RTCRtpReceiver Interface
The interface allows an application to inspect the
receipt of a RTCRtpReceiverMediaStreamTrack.
To create an RTCRtpReceiver with a string, kind, run the following steps:
-
Let receiver be a new
object.RTCRtpReceiver -
Let track be a new
MediaStreamTrackobject [GETUSERMEDIA]. The source of track is a remote source provided by receiver. Note that the track.idis generated by the user agent and does not map to any track IDs on the remote side. -
Initialize track.kind to kind.
-
Initialize track.label to the result of concatenating the string
"remote "with kind. -
Initialize track.readyState to
live. -
Initialize track.muted to
true. See the MediaStreamTrack section about how themutedattribute reflects if aMediaStreamTrackis receiving media data or not. -
Let receiver have a [[ReceiverTrack]] internal slot initialized to track.
-
Let receiver have a [[ReceiverTransport]] internal slot initialized to
null. -
Let receiver have a [[LastStableStateReceiverTransport]] internal slot initialized to
null. -
Let receiver have an [[AssociatedRemoteMediaStreams]] internal slot, representing a list of
MediaStreamobjects that theMediaStreamTrackobject of this receiver is associated with, and initialized to an empty list. -
Let receiver have a [[LastStableStateAssociatedRemoteMediaStreams]] internal slot and initialize it to an empty list.
-
Let receiver have a [[ReceiveCodecs]] internal slot, representing a list of
dictionaries, and initialized to an empty list.RTCRtpCodecParameters -
Let receiver have a [[LastStableStateReceiveCodecs]] internal slot and initialize it to an empty list.
-
Return receiver.
WebIDL[Exposed=Window] interfaceRTCRtpReceiver{ readonly attribute MediaStreamTracktrack; readonly attributeRTCDtlsTransport?transport; staticRTCRtpCapabilities?getCapabilities(DOMString kind);RTCRtpReceiveParametersgetParameters(); sequence<RTCRtpContributingSource>getContributingSources(); sequence<RTCRtpSynchronizationSource>getSynchronizationSources(); Promise<RTCStatsReport>getStats(); };
Attributes
-
trackof typeMediaStreamTrack, readonly -
The
attribute is the track that is associated with thistrackobject receiver.RTCRtpReceiverNote that
.trackstop()is final, although clones are not affected. Since receiver..trackstop()does not implicitly stop receiver, Receiver Reports continue to be sent. On getting, the attribute MUST return the value of the [[ReceiverTrack]] slot. -
transportof type, readonly, nullableRTCDtlsTransport -
The
attribute is the transport over which media for the receiver'stransportis received in the form of RTP packets. Prior to construction of thetrackobject, theRTCDtlsTransportattribute will betransportnull. When bundling is used, multipleobjects will share oneRTCRtpReceiverand will all receive RTP and RTCP over the same transport.transportOn getting, the attribute MUST return the value of the [[ReceiverTransport]] slot.
Methods
-
getCapabilities, static -
The
getCapabilities()method returns the most optimistic view of the capabilities of the system for receiving media of the given kind. It does not reserve any resources, ports, or other state but is meant to provide a way to discover the types of capabilities of the browser including which codecs may be supported. User agents MUST support kind values of"audio"and"video". If the system has no capabilities corresponding to the value of the kind argument,returnsgetCapabilitiesnull.These capabilities provide generally persistent cross-origin information on the device and thus increases the fingerprinting surface of the application. In privacy-sensitive contexts, browsers can consider mitigations such as reporting only a common subset of the capabilities.
NoteThe codec capabilities returned affect the
setCodecPreferences()algorithm and what inputs it throwsInvalidModificationErroron, and should also be consistent with information revealed bycreateOffer()andcreateAnswer()about codecs negotiated for reception, to ensure any privacy mitigations are effective. -
getParameters -
The
getParameters()method returns theobject's current parameters for howRTCRtpReceiveris decoded.trackWhen
is called, thegetParametersdictionary is constructed as follows:RTCRtpReceiveParameters- The
sequence is populated based on the header extensions that the receiver is currently prepared to receive.headerExtensions -
is set to the value of the [[ReceiveCodecs]] internal slot.codecsNoteBoth 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 from. But if the remote endpoint only answers with two, the absent codec will no longer be returned bygetParametersas the receiver no longer needs to be prepared to receive it.getParameters -
.rtcpis set toreducedSizetrueif the receiver is currently prepared to receive reduced-size RTCP packets, andfalseotherwise..rtcpis left out.cname
- The
-
getContributingSources -
Returns an
for each unique CSRC identifier received by thisRTCRtpContributingSourcein the last 10 seconds, in descendingRTCRtpReceiverorder.timestamp -
getSynchronizationSources -
Returns an
for each unique SSRC identifier received by thisRTCRtpSynchronizationSourcein the last 10 seconds, in descendingRTCRtpReceiverorder.timestamp -
getStats -
Gathers stats for this receiver only and reports the result asynchronously.
When the
getStats()method is invoked, the user agent MUST run the following steps:-
Let selector be the
object on which the method was invoked.RTCRtpReceiver -
Let p be a new promise, and run the following steps in parallel:
-
Gather the stats indicated by selector according to the stats selection algorithm.
-
Resolve p with the resulting
object, containing the gathered stats.RTCStatsReport
-
-
Return p.
-
The RTCRtpContributingSource and
RTCRtpSynchronizationSource 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 the
's RTCRtpReceiverMediaStreamTrack, the user agent MUST queue
a task to update the relevant information for the
and RTCRtpContributingSource
dictionaries based on the content of those packets. The information
relevant to the RTCRtpSynchronizationSource dictionary
corresponding to the SSRC identifier, is updated each time, and if an
RTP packet contains CSRC identifiers, then the information relevant
to the RTCRtpSynchronizationSource dictionaries corresponding to
those CSRC identifiers is also updated. The user agent MUST process
RTP packets in order of ascending RTP timestamps. The user agent MUST
keep information from RTP packets delivered to the
RTCRtpContributingSource's RTCRtpReceiverMediaStreamTrack in the previous 10 seconds.
MediaStreamTrack is not attached to any sink for
playout, getSynchronizationSources and
getContributingSources returns up-to-date
information as long as the track is not ended; sinks are not a
prerequisite for decoding RTP packets.
RTCRtpSynchronizationSource and
RTCRtpContributingSource dictionaries for a particular
RTCRtpReceiver contain information from a single point in the RTP
stream.
WebIDLdictionaryRTCRtpContributingSource{ required DOMHighResTimeStamptimestamp; required unsigned longsource; doubleaudioLevel; required unsigned longrtpTimestamp; };
Dictionary RTCRtpContributingSource Members
-
timestampof typeDOMHighResTimeStamp, required -
The
indicating the most recent time a frame from an RTP packet, originating from this source, was delivered to thetimestamp'sRTCRtpReceiverMediaStreamTrack. Theis defined astimestampPerformance.timeOrigin+Performance.now()at that time. -
sourceof type unsigned long, required -
The CSRC or SSRC identifier of the contributing or synchronization source.
-
audioLevelof type double -
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, this MUST be converted from the level value defined in [RFC6465] if the RFC 6465 header extension is present, otherwise this member MUST be absent.
For SSRCs, this MUST 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 value SHOULD 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). -
rtpTimestampof type unsigned long, required -
The last RTP timestamp, as defined in [RFC3550] Section 5.1, of the media played out at timestamp.
WebIDL dictionaryRTCRtpSynchronizationSource:RTCRtpContributingSource{ };
The dictionary is expected to serve as an extension point for the specification to surface data only available in SSRCs.RTCRtpSynchronizationSource
5.4
RTCRtpTransceiver Interface
The interface represents a combination of an
RTCRtpTransceiver and an RTCRtpSender that share a common media stream "identification-tag". As defined in [RFC8829] (section 3.4.1.), an RTCRtpReceiver is said
to be associated with a media description if its
"mid" property is non-null and matches a media stream
"identification-tag" in the media description; otherwise it
is said to be disassociated with that media description.
RTCRtpTransceiver
A may become associated with a new pending
description in RFC8829 while still being disassociated with the
current description. This may happen in check if negotiation is
needed.
RTCRtpTransceiver
The transceiver kind of an is
defined by the kind of the associated RTCRtpTransceiver's
RTCRtpReceiverMediaStreamTrack object.
To create an RTCRtpTransceiver with an
object, receiver, RTCRtpReceiver object,
sender, and an RTCRtpSender value,
direction, run the following steps:
RTCRtpTransceiverDirection
-
Let transceiver be a new
object.RTCRtpTransceiver -
Let transceiver have a [[Sender]] internal slot, initialized to sender.
-
Let transceiver have a [[Receiver]] internal slot, initialized to receiver.
-
Let transceiver have a [[Stopping]] internal slot, initialized to
false. -
Let transceiver have a [[Stopped]] internal slot, initialized to
false. -
Let transceiver have a [[Direction]] internal slot, initialized to direction.
-
Let transceiver have a [[Receptive]] internal slot, initialized to
false. -
Let transceiver have a [[CurrentDirection]] internal slot, initialized to
null. -
Let transceiver have a [[FiredDirection]] internal slot, initialized to
null. -
Let transceiver have a [[PreferredCodecs]] internal slot, initialized to an empty list.
-
Let transceiver have a [[JsepMid]] internal slot, initialized to
null. This is the "RtpTransceiver mid property" defined in [RFC8829] (section 5.2.1. and section 5.3.1.), and is only modified there. -
Let transceiver have a [[Mid]] internal slot, initialized to
null. -
Return transceiver.
RTCDtlsTransport and RTCIceTransport objects. This will only
occur as part of the process of setting a session description.
WebIDL[Exposed=Window] interfaceRTCRtpTransceiver{ readonly attribute DOMString?mid; [SameObject] readonly attributeRTCRtpSendersender; [SameObject] readonly attributeRTCRtpReceiverreceiver; attributeRTCRtpTransceiverDirectiondirection; readonly attributeRTCRtpTransceiverDirection?currentDirection; undefinedstop(); undefinedsetCodecPreferences(sequence<RTCRtpCodecCapability> codecs); };
Attributes
-
midof type DOMString, readonly, nullable -
The
attribute is the media stream "identification-tag" negotiated and present in the local and remote descriptions. On getting, the attribute MUST return the value of the [[Mid]] slot.mid -
senderof type, readonlyRTCRtpSender -
The
attribute exposes thesendercorresponding to the RTP media that may be sent with mid = [[Mid]]. On getting, the attribute MUST return the value of the [[Sender]] slot.RTCRtpSender -
receiverof type, readonlyRTCRtpReceiver -
The
attribute is thereceivercorresponding to the RTP media that may be received with mid = [[Mid]]. On getting the attribute MUST return the value of the [[Receiver]] slot.RTCRtpReceiver -
directionof typeRTCRtpTransceiverDirection -
As defined in [RFC8829] (section 4.2.4.), the direction attribute indicates the preferred direction of this transceiver, which will be used in calls to
andcreateOffer. An update of directionality does not take effect immediately. Instead, future calls tocreateAnswerandcreateOffermark the corresponding media description ascreateAnswersendrecv,sendonly,recvonlyorinactiveas defined in [RFC8829] (section 5.2.2. and section 5.3.2.)On getting, the user agent MUST run the following steps:
-
Let transceiver be the
object on which the getter is invoked.RTCRtpTransceiver -
If transceiver.[[Stopping]] is
true, return "".stopped -
Otherwise, return the value of the [[Direction]] slot.
On setting, the user agent MUST run the following steps:
-
Let transceiver be the
object on which the setter is invoked.RTCRtpTransceiver -
Let connection be the
object associated with transceiver.RTCPeerConnection -
If transceiver.[[Stopping]] is
true, throw anInvalidStateError. -
Let newDirection be the argument to the setter.
-
If newDirection is equal to transceiver.[[Direction]], abort these steps.
-
Set transceiver.[[Direction]] to newDirection.
-
Update the negotiation-needed flag for connection.
-
-
currentDirectionof type, readonly, nullableRTCRtpTransceiverDirection -
As defined in [RFC8829] (section 4.2.5.), the currentDirection attribute indicates the current direction negotiated for this transceiver. The value of currentDirection is independent of the value of
.RTCRtpEncodingParameterssince one cannot be deduced from the other. If this transceiver has never been represented in an offer/answer exchange, the value isactivenull. If the transceiver isstopped, the value is "".stoppedOn getting, the user agent MUST run the following steps:
-
Let transceiver be the
object on which the getter is invoked.RTCRtpTransceiver -
If transceiver.[[Stopped]] is
true, return "".stopped -
Otherwise, return the value of the [[CurrentDirection]] slot.
-
Methods
-
stop -
Irreversibly marks the transceiver as
stopping, unless it is alreadystopped. This will immediately cause the transceiver's sender to no longer send, and its receiver to no longer receive. Callingstop()also updates the negotiation-needed flag for the's associatedRTCRtpTransceiver.RTCPeerConnectionA stopping transceiver will cause future calls to
to generate a zero port in the media description for the corresponding transceiver, as defined in [RFC8829] (section 4.2.1.) (The user agent MUST treat acreateOfferstoppingtransceiver asstoppedfor the purposes of RFC8829 only in this case). However, to avoid problems with [RFC8843], a transceiver that isstopping, but notstopped, will not affect.createAnswerA stopped transceiver will cause future calls to
orcreateOfferto generate a zero port in the media description for the corresponding transceiver, as defined in [RFC8829] (section 4.2.1.).createAnswerThe transceiver will remain in the
stoppingstate, unless it becomesstoppedbyprocessing a rejected m-line in a remote offer or answer.setRemoteDescriptionNoteA transceiver that is
stoppingbut notstoppedwill always need negotiation. In practice, this means that callingstop()on a transceiver will cause the transceiver to becomestoppedeventually, provided negotiation is allowed to complete on both ends.When the
method is invoked, the user agent MUST run the following steps:stop-
Let transceiver be the
object on which the method is invoked.RTCRtpTransceiver -
Let connection be the
object associated with transceiver.RTCPeerConnection -
If connection.[[IsClosed]] is
true, throw anInvalidStateError. -
If transceiver.[[Stopping]] is
true, abort these steps. -
Stop sending and receiving with transceiver.
-
Update the negotiation-needed flag for connection.
The stop sending and receiving algorithm given a transceiver and, optionally, a disappear boolean defaulting to
false, is as follows:-
Let sender be transceiver.[[Sender]].
-
Let receiver be transceiver.[[Receiver]].
-
Stop sending media with sender.
-
Send an RTCP BYE for each RTP stream that was being sent by sender, as specified in [RFC3550].
-
Stop receiving media with receiver.
-
If disappear is
false, execute the steps for receiver.[[ReceiverTrack]] to be ended. This fires an event. -
Set transceiver.[[Direction]] to "
".inactive -
Set transceiver.[[Stopping]] to
true.
The stop the RTCRtpTransceiver algorithm given a transceiver and, optionally, a disappear boolean defaulting to
false, is as follows:-
If transceiver.[[Stopping]] is
false, stop sending and receiving with transceiver and disappear. -
Set transceiver.[[Stopped]] to
true. -
Set transceiver.[[Receptive]] to
false. -
Set transceiver.[[CurrentDirection]] to
null.
-
-
setCodecPreferences -
The
method overrides the default codec preferences used by the user agent. When generating a session description using eithersetCodecPreferencesorcreateOffer, the user agent MUST use the indicated codecs, in the order specified in the codecs argument, for the media section corresponding to thiscreateAnswer.RTCRtpTransceiverThis 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 list for sending.
Codec preferences remain in effect for all calls to
andcreateOfferthat include thiscreateAnsweruntil this method is called again. Setting codecs to an empty sequence resets codec preferences to any default value.RTCRtpTransceiverNoteCodecs 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 [RFC8829]. 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.
The codecs sequence passed into
can only contain codecs that are returned bysetCodecPreferences.RTCRtpSender(kind) orgetCapabilities.RTCRtpReceiver(kind), where kind is the kind of thegetCapabilitieson which the method is called. Additionally, theRTCRtpTransceiverdictionary members cannot be modified. If codecs does not fulfill these requirements, the user agent MUST throw anRTCRtpCodecCapabilityInvalidModificationError.NoteDue to a recommendation in [SDP], calls to
SHOULD 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.createAnswerWhen
setCodecPreferences()in invoked, the user agent MUST run the following steps:-
Let transceiver be the
object this method was invoked on.RTCRtpTransceiver -
Let codecs be the first argument.
-
If codecs is an empty list, set transceiver.[[PreferredCodecs]] to codecs and abort these steps.
-
Remove any duplicate values in codecs. 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.
-
Let kind be the transceiver's transceiver kind.
-
If the intersection between codecs and
.RTCRtpSender(kind).getCapabilitiesor the intersection between codecs andcodecs.RTCRtpReceiver(kind).getCapabilitiesonly contains RTX, RED or FEC codecs or is an empty set, throwcodecsInvalidModificationError. This ensures that we always have something to offer, regardless of transceiver..direction -
Let codecCapabilities be the union of
.RTCRtpSender(kind).getCapabilitiesandcodecs.RTCRtpReceiver(kind).getCapabilities.codecs -
For each codec in codecs,
- If codec is not in
codecCapabilities, throw
InvalidModificationError.
- If codec is not in
codecCapabilities, throw
-
Set transceiver.[[PreferredCodecs]] to codecs.
NoteIf set, the offerer's 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 functionality is provided via the
method of the
addTransceiver object and the RTCPeerConnection
method of the setParameters object.
RTCRtpSender
The method establishes the
simulcast envelope which includes the maximum number of
simulcast streams that can be sent, as well as the ordering of the
addTransceiver. While characteristics of
individual simulcast streams can be modified using the
encodings method, the simulcast envelope
cannot be changed. One of the implications of this model is that
the setParametersaddTrack() method cannot provide
simulcast functionality since it does not take
as an argument, and
therefore cannot configure an sendEncodings to send
simulcast.
RTCRtpTransceiver
Another implication is that the answerer cannot set the simulcast envelope directly. Upon calling the
method of the
setRemoteDescription object, the simulcast envelope is
configured on the RTCPeerConnection to contain the layers
described by the specified session description. Once the
envelope is determined, layers cannot be removed. They can be
marked as inactive by setting the
RTCRtpTransceiver member to activefalse
effectively disabling the layer.
While cannot modify the simulcast
envelope, it is still possible to control the number of streams
that are sent and the characteristics of those streams. Using
setParameters, simulcast streams can be made
inactive by setting the setParameters member
to activefalse, or can be reactivated by setting the
member to activetrue.
Using , stream characteristics can be
changed by modifying attributes such as
setParameters.
maxBitrate
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 same , 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.
maxBitrate
As defined in [RFC8829] (section 3.7.), an
offer from a user-agent will only contain a "send" description and
no "recv" description on the a=simulcast
line. Alternatives and restrictions (described in
[RFC8853]) are not supported.
This specification does not define how to configure reception of
multiple RTP encodings using ,
createOffer or
createAnswer. However when
addTransceiver is called with a
corresponding remote description that is able to send multiple RTP
encodings as defined in [RFC8829], and the browser supports
receiving multiple RTP encodings, the setRemoteDescription may
receive multiple RTP encodings and the parameters retrieved via the
transceiver's
RTCRtpReceiver.receivergetParameters()
will reflect the encodings negotiated.
An 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, the RTCRtpReceiver 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. An
RTCRtpReceiver 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.
RTCRtpReceiver
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 disabled
var 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, the attribute and the
direction method enable developers to implement
"hold" scenarios.
replaceTrack
To send music to a peer and cease rendering received audio (music-on-hold):
async function playMusicOnHold() {
try {
// Assume we have an audio transceiver and a music track named musicTrack
await 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:
async function handleSendonlyOffer() {
try {
// Apply the sendonly offer first,
// to ensure the receiver is ready for ICE candidates.
await pc.setRemoteDescription(sendonlyOffer);
// Stop sending audio
await audio.sender.replaceTrack(null);
// Align our direction to avoid further negotiation
audio.direction = 'recvonly';
// Call createAnswer and send a recvonly answer
await doAnswer();
} catch (err) {
// handle signaling error
}
}
To stop sending music and send audio captured from a microphone, as well to render received audio:
async function stopOnHoldMusic() {
// Assume we have an audio transceiver and a microphone track named micTrack
await 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:
async function onOffHold() {
try {
// Apply the sendrecv offer first, to ensure receiver is ready for ICE candidates.
await pc.setRemoteDescription(sendrecvOffer);
// Start sending audio
await audio.sender.replaceTrack(micTrack);
// Set the direction sendrecv (just in time for the answer)
audio.direction = 'sendrecv';
// Call createAnswer and send a sendrecv answer
await doAnswer();
} catch (err) {
// handle signaling error
}
}
5.5
RTCDtlsTransport Interface
The 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 by
RTCDtlsTransport and RTCRtpSender 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 the
RTCRtpReceiver interface allows access to information about the
underlying transport and the security added. RTCDtlsTransport
objects are constructed as a result of calls to
RTCDtlsTransportsetLocalDescription() and
setRemoteDescription(). Each
object represents the DTLS transport layer for
the RTP or RTCP RTCDtlsTransport of a specific
component, or a group of RTCRtpTransceivers if such a
group has been negotiated via [RFC8843].
RTCRtpTransceiver
RTCRtpTransceiver will be
represented by an existing RTCDtlsTransport object, whose
state will be updated accordingly, as opposed to
being represented by a new object.
An has a [[DtlsTransportState]]
internal slot initialized to "RTCDtlsTransport" and a
[[RemoteCertificates]] slot initialized to an empty list.
new
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 agent MUST queue a task that runs the following steps:
-
Let transport be the
object to receive the state update and error notification.RTCDtlsTransport -
If the state of transport is already "
", abort these steps.failed -
Set transport.[[DtlsTransportState]] to "
".failed -
Fire an event named
using theerrorinterface with its errorDetail attribute set to either "RTCErrorEvent" or "dtls-failure", as appropriate, and other fields set as described under thefingerprint-failureenum description, at transport.RTCErrorDetailType -
Fire an event named
at transport.statechange
When the underlying DTLS transport needs to update the state of the
corresponding object for any other reason, the
user agent MUST queue a task that runs the following steps:
RTCDtlsTransport
-
Let transport be the
object to receive the state update.RTCDtlsTransport -
Let newState be the new state.
-
Set transport.[[DtlsTransportState]] to newState.
-
If newState is
then let newRemoteCertificates be the certificate chain in use by the remote side, with each certificate encoded in binary Distinguished Encoding Rules (DER) [X690], and set transport.[[RemoteCertificates]] to newRemoteCertificates.connected -
Fire an event named
at transport.statechange
WebIDL[Exposed=Window] interfaceRTCDtlsTransport: EventTarget { [SameObject] readonly attributeRTCIceTransporticeTransport; readonly attributeRTCDtlsTransportStatestate; sequence<ArrayBuffer>getRemoteCertificates(); attribute EventHandleronstatechange; attribute EventHandleronerror; };
Attributes
-
iceTransportof type, readonlyRTCIceTransport -
The
attribute is the underlying transport that is used to send and receive packets. The underlying transport may not be shared between multiple activeiceTransportobjects.RTCDtlsTransport -
stateof type, readonlyRTCDtlsTransportState -
The
attribute MUST, on getting, return the value of the [[DtlsTransportState]] slot.state -
onstatechangeof type EventHandler -
The event type of this event handler is
.statechange -
onerrorof type EventHandler -
The event type of this event handler is
.error
Methods
-
getRemoteCertificates -
Returns the value of [[RemoteCertificates]].
RTCDtlsTransportState Enum
WebIDLenumRTCDtlsTransportState{ "new", "connecting", "connected", "closed", "failed" };
| Enumeration description | |
|---|---|
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 calling
().
|
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.1
RTCDtlsFingerprint Dictionary
The dictionary includes the hash function
algorithm and certificate fingerprint as described in [RFC4572].
RTCDtlsFingerprint
WebIDLdictionaryRTCDtlsFingerprint{ DOMStringalgorithm; DOMStringvalue; };
Dictionary RTCDtlsFingerprint Members
-
algorithmof type DOMString -
One of the the hash function algorithms defined in the 'Hash function Textual Names' registry [IANA-HASH-FUNCTION].
-
valueof type DOMString -
The value of the certificate fingerprint in lowercase hex string as expressed utilizing the syntax of 'fingerprint' in [RFC4572] Section 5.
5.6
RTCIceTransport Interface
The 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 to
RTCIceTransportsetLocalDescription() and
setRemoteDescription(). The underlying ICE
state is managed by the ICE agent; as such, the state of an
changes when the ICE Agent provides
indications to the user agent as described below. Each
RTCIceTransport object represents the ICE transport layer for the
RTP or RTCP RTCIceTransport of a specific
component, or a group of RTCRtpTransceivers if such a
group has been negotiated via [RFC8843].
RTCRtpTransceiver
RTCRtpTransceiver will be
represented by an existing RTCIceTransport object, whose
state will be updated accordingly, as opposed to
being represented by a new object.
When the ICE Agent indicates that it began gathering a generation of candidates for an , the user
agent MUST queue a task that runs the following steps:
RTCIceTransport
-
Let connection be the
object associated with this ICE Agent.RTCPeerConnection -
If connection.[[IsClosed]] is
true, abort these steps. -
Let transport be the
for which candidate gathering began.RTCIceTransport -
Set transport.[[IceGathererState]] to
.gathering -
Fire an event named
at transport.gatheringstatechange -
Update the ICE gathering state of connection.
When the ICE Agent is finished gathering a generation of
candidates for an , and those candidates have been
surfaced to the application, the user agent MUST queue a task that
runs the following steps:
RTCIceTransport
-
Let connection be the
object associated with this ICE Agent.RTCPeerConnection -
If connection.[[IsClosed]] is
true, abort these steps. -
Let transport be the
for which candidate gathering finished.RTCIceTransport -
Let newCandidate be the result of creating an RTCIceCandidate with a new dictionary whose
andsdpMidare set to the values associated with thissdpMLineIndex,RTCIceTransportis set to the username fragment of the generation of candidates for which gathering finished, andusernameFragmentis set to an empty string.candidate -
Fire an event named
using theicecandidateinterface with the candidate attribute set to newCandidate at connection.RTCPeerConnectionIceEvent -
If another generation of candidates is still being gathered, abort these steps.
NoteThis may occur if an ICE restart is initiated while the ICE agent is still gathering the previous generation of candidates. -
Set transport.[[IceGathererState]] to
.complete -
Fire an event named
at transport.gatheringstatechange -
Update the ICE gathering state of connection.
When the ICE Agent indicates that a new ICE candidate is
available for an , either by taking one from the
ICE candidate pool or gathering it
from scratch, the user agent MUST queue a task that runs the
following steps:
RTCIceTransport
-
Let candidate be the available ICE candidate.
-
Let connection be the
object associated with this ICE Agent.RTCPeerConnection -
If connection.[[IsClosed]] is
true, abort these steps. -
If either connection.[[PendingLocalDescription]] or connection.[[CurrentLocalDescription]] are not
null, and represent the ICE generation for which candidate was gathered, surface the candidate with candidate and connection, and abort these steps. -
Otherwise, append candidate to connection.[[EarlyCandidates]].
When the ICE 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.
To release early candidates of a connection, run the following steps:
-
For each candidate, candidate, in connection.[[EarlyCandidates]], queue a task to surface the candidate with candidate and connection.
-
Set connection.[[EarlyCandidates]] to an empty list.
To surface a candidate with candidate and connection, run the following steps:
-
If connection.[[IsClosed]] is
true, abort these steps. -
Let transport be the
for which candidate is being made available.RTCIceTransport -
If connection.[[PendingLocalDescription]] is not
null, and represents the ICE generation for which candidate was gathered, add candidate to connection.[[PendingLocalDescription]].sdp. -
If connection.[[CurrentLocalDescription]] is not
null, and represents the ICE generation for which candidate was gathered, add candidate to connection.[[CurrentLocalDescription]].sdp. -
Let newCandidate be the result of creating an RTCIceCandidate with a new dictionary whose
andsdpMidare set to the values associated with thissdpMLineIndex,RTCIceTransportis set to the username fragment of the candidate, andusernameFragmentis set to a string encoded using thecandidatecandidate-attributegrammar to represent candidate. -
Add newCandidate to transport's set of local candidates.
-
Fire an event named
using theicecandidateinterface with the candidate attribute set to newCandidate at connection.RTCPeerConnectionIceEvent
The of an RTCIceTransportState 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 and RTCIceTransport are related
and are handled in the same task.
RTCIceTransportState
When the ICE Agent indicates that an has
changed either the selected candidate pair, the
RTCIceTransport or both, the user agent MUST queue a task
that runs the following steps:
RTCIceTransportState
-
Let connection be the
object associated with this ICE Agent.RTCPeerConnection -
If connection.[[IsClosed]] is
true, abort these steps. -
Let transport be the
whose state is changing.RTCIceTransport -
Let selectedCandidatePairChanged be
false. -
Let transportIceConnectionStateChanged be
false. -
Let connectionIceConnectionStateChanged be
false. -
Let connectionStateChanged be
false. -
If transport's selected candidate pair was changed, run the following steps:
-
Let newCandidatePair be a newly created
representing the indicated pair if one is selected, andRTCIceCandidatePairnullotherwise. -
Set transport.[[SelectedCandidatePair]] to newCandidatePair.
-
Set selectedCandidatePairChanged to
true.
-
-
If transport's
was changed, run the following steps:RTCIceTransportState-
Set transport.[[IceTransportState]] to the new indicated
.RTCIceTransportState -
Set transportIceConnectionStateChanged to
true. -
Set connection's ICE connection state to the value of deriving a new state value as described by the
enum.RTCIceConnectionState -
If the ice connection state changed in the previous step, set connectionIceConnectionStateChanged to
true. -
Set connection's connection state to the value of deriving a new state value as described by the
enum.RTCPeerConnectionState -
If the connection state changed in the previous step, set connectionStateChanged to
true.
-
-
If selectedCandidatePairChanged is
true, fire an event namedat transport.selectedcandidatepairchange -
If transportIceConnectionStateChanged is
true, fire an event namedat transport.statechange -
If connectionIceConnectionStateChanged is
true, fire an event namedat connection.iceconnectionstatechange -
If connectionStateChanged is
true, fire an event namedat connection.connectionstatechange
An object has the following internal slots:
RTCIceTransport
-
[[IceTransportState]] initialized to
"
"new -
[[IceGathererState]] initialized to
"
"new -
[[SelectedCandidatePair]] initialized to
null -
[[IceRole]] initialized to "
"unknown
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(); attribute EventHandleronstatechange; attribute EventHandlerongatheringstatechange; attribute EventHandleronselectedcandidatepairchange; };
Attributes
-
roleof type, readonlyRTCIceRole -
The
attribute MUST, on getting, return the value of the [[IceRole]] internal slot.role -
componentof type, readonlyRTCIceComponent -
The
attribute MUST return the ICE component of the transport. When RTCP mux is used, a singlecomponenttransports both RTP and RTCP andRTCIceTransportis set to "component".rtp -
stateof type, readonlyRTCIceTransportState -
The
attribute MUST, on getting, return the value of the [[IceTransportState]] slot.state -
gatheringStateof type, readonlyRTCIceGathererState -
The
attribute MUST, on getting, return the value of the [[IceGathererState]] slot.gatheringState -
onstatechangeof type EventHandler -
This event handler, of event handler event type
, MUST be fired any time thestatechangeRTCIceTransportchanges.state -
ongatheringstatechangeof type EventHandler -
This event handler, of event handler event type
, MUST be fired any time thegatheringstatechangeICE gathering state changes.RTCIceTransport -
onselectedcandidatepairchangeof type EventHandler -
This event handler, of event handler event type
, MUST be fired any time theselectedcandidatepairchange's selected candidate pair changes.RTCIceTransport
Methods
-
getLocalCandidates -
Returns a sequence describing the local ICE candidates gathered for this
and sent inRTCIceTransport.onicecandidate -
getRemoteCandidates -
Returns a sequence describing the remote ICE candidates received by this
viaRTCIceTransportaddIceCandidate().Notewill not expose peer reflexive candidates since they are not received viagetRemoteCandidatesaddIceCandidate(). -
getSelectedCandidatePair -
Returns the selected candidate pair on which packets are sent. This method MUST return the value of the [[SelectedCandidatePair]] slot. When
.RTCIceTransportis "state" or "new"closedreturnsgetSelectedCandidatePairnull. -
getLocalParameters -
Returns the local ICE parameters received by this
viaRTCIceTransport, orsetLocalDescriptionnullif the parameters have not yet been received. -
getRemoteParameters -
Returns the remote ICE parameters received by this
viaRTCIceTransportorsetRemoteDescriptionnullif the parameters have not yet been received.
5.6.1
RTCIceParameters Dictionary
WebIDLdictionaryRTCIceParameters{ DOMStringusernameFragment; DOMStringpassword; };
Dictionary RTCIceParameters Members
RTCIceParameters5.6.2
RTCIceCandidatePair Dictionary
WebIDLdictionaryRTCIceCandidatePair{RTCIceCandidatelocal;RTCIceCandidateremote; };
Dictionary RTCIceCandidatePair Members
RTCIceCandidatePair-
localof typeRTCIceCandidate -
The local ICE candidate.
-
remoteof typeRTCIceCandidate -
The remote ICE candidate.
5.6.3
RTCIceGathererState Enum
WebIDLenumRTCIceGathererState{ "new", "gathering", "complete" };
Enumeration description
|
|
|---|---|
new
|
The was just created, and has not
started gathering candidates yet.
|
gathering
|
The is in the process of gathering
candidates.
|
complete
|
The 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.4
RTCIceTransportState Enum
WebIDLenumRTCIceTransportState{ "new", "checking", "connected", "completed", "disconnected", "failed", "closed" };
Enumeration description
|
|
|---|---|
new
|
The is gathering candidates and/or
waiting for remote candidates to be supplied, and has not
yet started checking.
|
checking
|
The has received at least one remote
candidate 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.
|
connected
|
The 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 ""
(if there are candidate pairs remaining to be checked) or
"" (if there are no
candidate pairs to check, but the peer is still gathering
and/or waiting for additional remote candidates).
|
completed
|
The 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 "".
|
disconnected
|
The ICE Agent has determined that connectivity is
currently lost for this . 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:
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.
|
failed
|
The 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 have lost consent.
This is a terminal state until ICE is restarted. Since an
ICE restart may cause connectivity to resume, entering the
"" state does not cause DTLS
transports, SCTP associations or the data channels that run
over them to close, or tracks to mute.
|
closed
|
The has shut down and is no longer
responding to STUN requests.
|
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
"" to
"checking".
completed
An ICE restart causes candidate gathering and connectivity checks to
begin anew, causing a transition to
"" if begun in the
"connected" state. If begun in the
transient "completed" state, it causes
a transition to "disconnected", effectively
forgetting that connectivity was previously lost.
checking
The "" and
"failed" states require an indication
that there are no additional remote candidates. This can be
indicated by calling completed with a
candidate value whose addIceCandidate property is set
to an empty string or by
candidate being set to
canTrickleIceCandidatesfalse.
Some example state transitions are:
- (
first created, as a result ofRTCIceTransportorsetLocalDescription): "setRemoteDescription"new - ("
", remote candidates received): "new"checking - ("
", found usable connection): "checking"connected - ("
", checks fail but gathering still in progress): "checking"disconnected - ("
", gave up): "checking"failed - ("
", new local candidates): "disconnected"checking - ("
", finished all checks): "connected"completed - ("
", lost connectivity): "completed"disconnected - ("
" or "disconnected", ICE restart occurs): "failed"checking - ("
", ICE restart occurs): "completed"connected .RTCPeerConnectionclose(): ""closed
5.6.5
RTCIceRole Enum
WebIDLenumRTCIceRole{ "unknown", "controlling", "controlled" };
Enumeration description
|
|
|---|---|
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.6
RTCIceComponent Enum
WebIDLenumRTCIceComponent{ "rtp", "rtcp" };
Enumeration description
|
|
|---|---|
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 the component-id value 1 when encoded
in candidate-attribute.
|
rtcp
|
The ICE Transport is used for RTCP as defined by [RFC5245],
Section 4.1.1.1. This represents the component-id value 2 when encoded
in candidate-attribute.
|
5.7
RTCTrackEvent
The event uses the track interface.
RTCTrackEvent
WebIDL[Exposed=Window] interfaceRTCTrackEvent: Event {constructor(DOMString type,RTCTrackEventIniteventInitDict); readonly attributeRTCRtpReceiverreceiver; readonly attribute MediaStreamTracktrack; [SameObject] readonly attribute FrozenArray<MediaStream>streams; readonly attributeRTCRtpTransceivertransceiver; };
Constructors
-
RTCTrackEvent.constructor()
Attributes
-
receiverof type, readonlyRTCRtpReceiver -
The
attribute represents thereceiverobject associated with the event.RTCRtpReceiver -
trackof typeMediaStreamTrack, readonly -
The
attribute represents thetrackMediaStreamTrackobject that is associated with theidentified byRTCRtpReceiver.receiver -
streamsof type FrozenArray<MediaStream>, readonly -
The
attribute returns an array ofstreamsMediaStreamobjects representing theMediaStreams that this event'sis a part of.track -
transceiverof type, readonlyRTCRtpTransceiver -
The
attribute represents thetransceiverobject associated with the event.RTCRtpTransceiver
WebIDLdictionaryRTCTrackEventInit: EventInit { requiredRTCRtpReceiverreceiver; required MediaStreamTracktrack; sequence<MediaStream>streams= []; requiredRTCRtpTransceivertransceiver; };
Dictionary RTCTrackEventInit Members
-
receiverof type, requiredRTCRtpReceiver -
The
member represents thereceiverobject associated with the event.RTCRtpReceiver -
trackof typeMediaStreamTrack, required -
The
member represents thetrackMediaStreamTrackobject that is associated with theidentified byRTCRtpReceiver.receiver -
streamsof type sequence<MediaStream>, defaulting to[] -
The
member is an array ofstreamsMediaStreamobjects representing theMediaStreams that this event'sis a part of.track -
transceiverof type, requiredRTCRtpTransceiver -
The
attribute represents thetransceiverobject associated with the event.RTCRtpTransceiver
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 of Web Sockets.
6.1 RTCPeerConnection Interface Extensions
The Peer-to-peer data API extends the interface
as described below.
RTCPeerConnection
WebIDL partial interfaceRTCPeerConnection{ readonly attributeRTCSctpTransport?sctp;RTCDataChannelcreateDataChannel(USVString label, optionalRTCDataChannelInitdataChannelDict = {}); attribute EventHandlerondatachannel; };
Attributes
-
sctpof type, readonly, nullableRTCSctpTransport -
The SCTP transport over which SCTP data is sent and received. If SCTP has not been negotiated, the value is null. This attribute MUST return the
object stored in the [[SctpTransport]] internal slot.RTCSctpTransport -
ondatachannelof type EventHandler -
The event type of this event handler is
datachannel.
Methods
-
createDataChannel -
Creates a new
object with the given label. TheRTCDataChanneldictionary can be used to configure properties of the underlying channel such as data reliability.RTCDataChannelInitWhen the
method is invoked, the user agent MUST run the following steps.createDataChannel-
Let connection be the
object on which the method is invoked.RTCPeerConnection -
If connection.[[IsClosed]] is
true, throw anInvalidStateError. -
Create an RTCDataChannel, channel.
-
Initialize channel.[[DataChannelLabel]] to the value of the first argument.
-
If the UTF-8 representation of [[DataChannelLabel]] is longer than 65535 bytes, throw a
TypeError. -
Let options be the second argument.
-
Initialize channel.[[MaxPacketLifeTime]] to option.
, if present, otherwisemaxPacketLifeTimenull. -
Initialize channel.[[MaxRetransmits]] to option.
, if present, otherwisemaxRetransmitsnull. -
Initialize channel.[[Ordered]] to option.
.ordered -
Initialize channel.[[DataChannelProtocol]] to option.
.protocol -
If the UTF-8 representation of [[DataChannelProtocol]] is longer than 65535 bytes, throw a
TypeError. -
Initialize channel.[[Negotiated]] to option.
.negotiated -
Initialize channel.[[DataChannelId]] to the value of option.
, if it is present and [[Negotiated]] is true, otherwiseidnull. -
If [[Negotiated]] is
trueand [[DataChannelId]] isnull, throw aTypeError. -
If both [[MaxPacketLifeTime]] and [[MaxRetransmits]] attributes are set (not null), throw a
TypeError. -
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 value MUST be set to the user agents maximum value.
-
If [[DataChannelId]] is equal to 65535, which is greater than the maximum allowed ID of 65534 but still qualifies as an unsigned short, throw a
TypeError. -
If the [[DataChannelId]] slot is
null(due to no ID being passed into, 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 existingcreateDataChannel, throw anRTCDataChannelOperationErrorexception.NoteIf the [[DataChannelId]] slot isnullafter this step, it will be populated during the RTCSctpTransport connected procedure. -
Let transport be connection.[[SctpTransport]].
If the [[DataChannelId]] slot is not
null, transport is in the "" state and [[DataChannelId]] is greater or equal to transport.[[MaxChannels]], throw anconnectedOperationError. -
If channel is the first
created on connection, update the negotiation-needed flag for connection.RTCDataChannel -
Return channel and continue the following steps in parallel.
-
Create channel's associated underlying data transport and configure it according to the relevant properties of channel.
-
6.1.1
RTCSctpTransport Interface
The interface allows an application access to
information about the SCTP data channels tied to a particular SCTP
association.
RTCSctpTransport
6.1.1.1 Create an instance
To create an with an initial
state, initialState, run the following steps:
RTCSctpTransport
-
Let transport be a new
object.RTCSctpTransport -
Let transport have a [[SctpTransportState]] internal slot initialized to initialState.
-
Let transport have a [[MaxMessageSize]] internal slot and run the steps labeled update the data max message size to initialize it.
-
Let transport have a [[MaxChannels]] internal slot initialized to
null. -
Return transport.
6.1.1.2 Update max message size
To update the data max message size of an
run the following steps:
RTCSctpTransport
-
Let transport be the
object to be updated.RTCSctpTransport -
Let remoteMaxMessageSize be the value of the
max-message-sizeSDP attribute read from the remote description, as described in [RFC8841] (section 6), or 65536 if the attribute is missing. -
Let canSendSize 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.
-
If both remoteMaxMessageSize and canSendSize are 0, set [[MaxMessageSize]] to the positive Infinity value.
-
Else, if either remoteMaxMessageSize or canSendSize is 0, set [[MaxMessageSize]] to the larger of the two.
-
Else, set [[MaxMessageSize]] to the smaller of remoteMaxMessageSize or canSendSize.
6.1.1.3 Connected procedure
Once an SCTP transport
is connected, meaning the SCTP association of an has been established, run the following steps:
RTCSctpTransport
-
Let transport be the
object.RTCSctpTransport -
Let connection be the
object associated with transport.RTCPeerConnection -
Set [[MaxChannels]] to the minimum of the negotiated amount of incoming and outgoing SCTP streams.
-
For each of connection's
:RTCDataChannel-
Let channel be the
object.RTCDataChannel -
If channel.[[DataChannelId]] is
null, initialize [[DataChannelId]] to the value generated by the underlying sctp data channel, according to [RFC8832]. -
If channel.[[DataChannelId]] is greater or equal to transport.[[MaxChannels]], or the previous step failed to assign an id, close the channel due to a failure. Otherwise, announce the channel as open.
-
-
Fire an event named
at transport.statechangeNoteThis event is fired before the
openevents fired by announcing the channel as open; theopenevents are fired from a queued task.
WebIDL[Exposed=Window] interfaceRTCSctpTransport: EventTarget { readonly attributeRTCDtlsTransporttransport; readonly attributeRTCSctpTransportStatestate; readonly attribute unrestricted doublemaxMessageSize; readonly attribute unsigned short?maxChannels; attribute EventHandleronstatechange; };
Attributes
-
transportof type, readonlyRTCDtlsTransport -
The transport over which all SCTP packets for data channels will be sent and received.
-
stateof type, readonlyRTCSctpTransportState -
The current state of the SCTP transport. On getting, this attribute MUST return the value of the [[SctpTransportState]] slot.
-
maxMessageSizeof type unrestricted double, readonly -
The maximum size of data that can be passed to
'sRTCDataChannelsend()method. The attribute MUST, on getting, return the value of the [[MaxMessageSize]] slot. -
maxChannelsof type unsigned short , readonly, nullable -
The maximum amount of
's that can be used simultaneously. The attribute MUST, on getting, return the value of the [[MaxChannels]] slot.RTCDataChannelNoteThis attribute's value will benulluntil the SCTP transport goes into the "" state.connected -
onstatechangeof type EventHandler -
The event type of this event handler is
.statechange
6.1.2
RTCSctpTransportState Enum
indicates the state of the SCTP
transport.
RTCSctpTransportState
WebIDLenumRTCSctpTransportState{ "connecting", "connected", "closed" };
| Enumeration description | |
|---|---|
connecting
|
The |
connected
|
When the negotiation of an association is completed, a
task is queued to update the [[SctpTransportState]] slot
to " |
closed
|
A task is queued to update the [[SctpTransportState]]
slot to "
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.2
RTCDataChannel
The interface represents a bi-directional data
channel between two peers. An RTCDataChannel is created via a
factory method on an RTCDataChannel object. The messages sent
between the browsers are described in [RFC8831] and
[RFC8832].
RTCPeerConnection
There are two ways to establish a connection with .
The first way is to simply create an RTCDataChannel at one of the
peers with the RTCDataChannelnegotiated dictionary member unset or set to its default
value false. This will announce the new channel in-band and trigger
an RTCDataChannelInit with the corresponding RTCDataChannelEvent
object at the other peer. The second way is to let the application
negotiate the RTCDataChannel. To do this, create an
RTCDataChannel object with the RTCDataChannelnegotiated dictionary member set to true, and signal
out-of-band (e.g. via a web server) to the other side that it SHOULD
create a corresponding RTCDataChannelInit with the
RTCDataChannelnegotiated dictionary
member set to true and the same RTCDataChannelInit. This will
connect the two separately created id objects. The
second way makes it possible to create channels with asymmetric
properties and to create channels in a declarative way by specifying
matching RTCDataChannels.
id
Each has an associated underlying data transport that is used to
transport actual data to the other peer. In the case of SCTP data
channels utilizing an RTCDataChannel (which represents the
state of the SCTP association), the underlying data transport is the
SCTP stream pair. The transport properties of the underlying 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].
RTCSctpTransport
An 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 (
RTCDataChannel ) or set a time during which
transmissions (including retransmissions) are allowed (
maxRetransmits ). 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.
maxPacketLifeTime
An , created with
RTCDataChannel or dispatched via an
createDataChannel, MUST initially be in the
"RTCDataChannelEvent" state. When the
connecting object's underlying data transport is ready,
the user agent MUST announce the RTCDataChannel as open.
RTCDataChannel
6.2.1 Creating a data channel
To create an , run the following
steps:
RTCDataChannel
-
Let channel be a newly created
object.RTCDataChannel -
Let channel have a [[ReadyState]] internal slot initialized to "
".connecting -
Let channel have a [[BufferedAmount]] internal slot initialized to
0. -
Let channel have internal slots named [[DataChannelLabel]], [[Ordered]], [[MaxPacketLifeTime]], [[MaxRetransmits]], [[DataChannelProtocol]], [[Negotiated]], and [[DataChannelId]].
-
Return channel.
6.2.2 Announcing a data channel as open
When the user agent is to announce an as
open, the user agent MUST queue a task to run the following
steps:
RTCDataChannel
-
If the associated
object's [[IsClosed]] slot isRTCPeerConnectiontrue, abort these steps. -
Let channel be the
object to be announced.RTCDataChannel -
If channel.[[ReadyState]] is "
" or "closing", abort these steps.closed -
Set channel.[[ReadyState]] to "
".open -
Fire an event named
at channel.open
6.2.3 Announcing a data channel instance
When an underlying data transport is to be announced (the
other peer created a channel with
unset or set to false), the user agent of the peer that did not
initiate the creation process MUST queue a task to run the
following steps:
negotiated
-
Let connection be the
object associated with the underlying data transport.RTCPeerConnection -
If connection.[[IsClosed]] is
true, abort these steps. -
Create an RTCDataChannel, channel.
-
Let configuration be an information bundle received from the other peer as a part of the process to establish the underlying data transport described by the WebRTC DataChannel Protocol specification [RFC8832].
-
Initialize channel.[[DataChannelLabel]], [[Ordered]], [[MaxPacketLifeTime]], [[MaxRetransmits]], [[DataChannelProtocol]], and [[DataChannelId]] internal slots to the corresponding values in configuration.
-
Initialize channel.[[Negotiated]] to
false. -
Set channel.[[ReadyState]] to "
" (but do not fire theopenevent, yet).openNoteThis allows to start sending messages inside of thedatachannelevent handler prior to theevent being fired.open -
Fire an event named
datachannelusing theinterface with theRTCDataChannelEventattribute set to channel at connection.channel
6.2.4 Closing procedure
An object's underlying data transport may
be torn down in a non-abrupt manner by running the closing procedure. When
that happens the user agent MUST queue a task to run the following
steps:
RTCDataChannel
-
Let channel be the
object whose underlying data transport was closed.RTCDataChannel -
Unless the procedure was initiated by channel.
, set channel.[[ReadyState]] to "close" and fire an event namedclosingat channel.closing -
Run the following steps in parallel:
-
Finish sending all currently pending messages of the channel.
-
Follow the closing procedure defined for the channel's underlying data transport :
-
Render the channel's data transport
closedby following the associated procedure.
-
6.2.5 Announcing a data channel as closed
When an object's underlying data transport
has been closed, the user agent MUST queue a task to run the
following steps:
RTCDataChannel
-
Let channel be the
object whose underlying data transport was closed.RTCDataChannel - If channel.[[ReadyState]] is
"
", abort these steps.closed -
Set channel.[[ReadyState]] to "
".closed -
If the transport was closed with an error, fire an event named
using theerrorinterface with itsRTCErrorEventattribute set to "errorDetail" at channel.sctp-failure -
Fire an event named
at channel.close
6.2.6 Error on creating data channels
In some cases, the user agent may be unable to create an
's underlying data transport. For
example, the data channel's RTCDataChannel may be outside
the range negotiated by the [RFC8831] implementations in the
SCTP handshake. When the user agent determines that an
id's underlying data transport cannot be
created, the user agent MUST queue a task to run the following
steps:
RTCDataChannel
-
Let channel be the
object for which the user agent could not create an underlying data transport.RTCDataChannel -
Set channel.[[ReadyState]] to "
".closed -
Fire an event named
using theerrorinterface with theRTCErrorEventattribute set to "errorDetail" at channel.data-channel-failure -
Fire an event named
at channel.close
6.2.7 Receiving messages on a data channel
When an message has
been received via the underlying data transport with
type type and data rawData, the user agent
MUST queue a task to run the following steps:
RTCDataChannel
-
Let channel be the
object for which the user agent has received a message.RTCDataChannel -
Let connection be the
object associated with channel.RTCPeerConnection -
If channel.[[ReadyState]] is not "
", abort these steps and discard rawData.open -
Execute the sub step by switching on type and channel.
:binaryType-
If type indicates that rawData is a
string:Let data be a DOMString that represents the result of decoding rawData as UTF-8.
-
If type indicates that rawData is binary and
isbinaryType"blob":Let data be a new
Blobobject containing rawData as its raw data source. -
If type indicates that rawData is binary and
isbinaryType"arraybuffer":Let data be a new
ArrayBufferobject containing rawData as its raw data source.
-
-
Fire an event named
using themessageMessageEventinterface with itsoriginattribute initialized to the serialization of an origin of connection.[[DocumentOrigin]], and thedataattribute initialized to data at channel.
WebIDL[Exposed=Window] interfaceRTCDataChannel: EventTarget { readonly attribute USVStringlabel; readonly attribute booleanordered; readonly attribute unsigned short?maxPacketLifeTime; readonly attribute unsigned short?maxRetransmits; readonly attribute USVStringprotocol; readonly attribute booleannegotiated; readonly attribute unsigned short?id; readonly attributeRTCDataChannelStatereadyState; readonly attribute unsigned longbufferedAmount; [EnforceRange] attribute unsigned longbufferedAmountLowThreshold; attribute EventHandleronopen; attribute EventHandleronbufferedamountlow; attribute EventHandleronerror; attribute EventHandleronclosing; attribute EventHandleronclose; undefinedclose(); attribute EventHandleronmessage; attribute BinaryTypebinaryType; undefinedsend(USVString data); undefinedsend(Blob data); undefinedsend(ArrayBuffer data); undefinedsend(ArrayBufferView data); };
Attributes
-
labelof type USVString, readonly -
The
attribute represents a label that can be used to distinguish thislabelobject from otherRTCDataChannelobjects. Scripts are allowed to create multipleRTCDataChannelobjects with the same label. On getting, the attribute MUST return the value of the [[DataChannelLabel]] slot.RTCDataChannel -
orderedof type boolean, readonly -
The
attribute returns true if theorderedis ordered, and false if out of order delivery is allowed. On getting, the attribute MUST return the value of the [[Ordered]] slot.RTCDataChannel -
maxPacketLifeTimeof type unsigned short, readonly, nullable -
The
attribute returns the length of the time window (in milliseconds) during which transmissions and retransmissions may occur in unreliable mode. On getting, the attribute MUST return the value of the [[MaxPacketLifeTime]] slot.maxPacketLifeTime -
maxRetransmitsof type unsigned short, readonly, nullable -
The
attribute returns the maximum number of retransmissions that are attempted in unreliable mode. On getting, the attribute MUST return the value of the [[MaxRetransmits]] slot.maxRetransmits -
protocolof type USVString, readonly -
The
attribute returns the name of the sub-protocol used with thisprotocol. On getting, the attribute MUST return the value of the [[DataChannelProtocol]] slot.RTCDataChannel -
negotiatedof type boolean, readonly -
The
attribute returns true if thisnegotiatedwas negotiated by the application, or false otherwise. On getting, the attribute MUST return the value of the [[Negotiated]] slot.RTCDataChannel -
idof type unsigned short, readonly, nullable -
The
attribute returns the ID for thisid. 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 attribute MUST return the value of the [[DataChannelId]] slot.RTCDataChannel -
readyStateof type, readonlyRTCDataChannelState -
The
attribute represents the state of thereadyStateobject. On getting, the attribute MUST return the value of the [[ReadyState]] slot.RTCDataChannel -
bufferedAmountof type unsigned long, readonly -
The
attribute MUST, 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 usingbufferedAmountsend(). Even though the data transmission can occur in parallel, the returned value MUST 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 ""; however, the slot does not reset to zero once the channel closes. When the underlying data transport sends data from its queue, the user agent MUST queue a task that reduces [[BufferedAmount]] with the number of bytes that was sent.open -
bufferedAmountLowThresholdof type unsigned long -
The
attribute sets the threshold at which thebufferedAmountLowThresholdis considered to be low. When thebufferedAmountdecreases from above this threshold to equal or below it, thebufferedAmountevent fires. Thebufferedamountlowis initially zero on each newbufferedAmountLowThreshold, but the application may change its value at any time.RTCDataChannel -
onopenof type EventHandler -
The event type of this event handler is
.open -
onbufferedamountlowof type EventHandler -
The event type of this event handler is
.bufferedamountlow -
onerrorof type EventHandler -
The event type of this event handler is
.RTCErrorEventcontains "sctp-failure",errorDetailcontains the SCTP Cause Code value, andsctpCauseCodecontains the SCTP Cause-Specific-Information, possibly with additional text.message -
onclosingof type EventHandler -
The event type of this event handler is
.closing -
oncloseof type EventHandler -
The event type of this event handler is
.close -
onmessageof type EventHandler -
The event type of this event handler is
.message -
binaryTypeof type BinaryType -
The
attribute MUST, on getting, return the value to which it was last set. On setting, if the new value is either the stringbinaryType"blob"or the string"arraybuffer", then set the IDL attribute to this new value. Otherwise, throw aSyntaxError. When anobject is created, theRTCDataChannelattribute MUST be initialized to the stringbinaryType"blob".This attribute controls how binary data is exposed to scripts. See Web Socket's
binaryType.
Methods
-
close -
Closes the
. It may be called regardless of whether theRTCDataChannelobject was created by this peer or the remote peer.RTCDataChannelWhen the
method is called, the user agent MUST run the following steps:close-
Let channel be the
object which is about to be closed.RTCDataChannel -
If channel.[[ReadyState]] is "
" or "closing", then abort these steps.closed -
Set channel.[[ReadyState]] to "
".closing -
If the closing procedure has not started yet, start it.
-
-
send -
Run the steps described by the send() algorithm with argument type
stringobject. -
send -
Run the steps described by the send() algorithm with argument type
Blobobject. -
send -
Run the steps described by the send() algorithm with argument type
ArrayBufferobject. -
send -
Run the steps described by the send() algorithm with argument type
ArrayBufferViewobject.
The send() method is overloaded to
handle different data argument types. When any version of the
method is called, the user agent MUST run the following
steps:
-
Let channel be the
object on which data is to be sent.RTCDataChannel -
If channel.[[ReadyState]] is not "
", throw anopenInvalidStateError. -
Execute the sub step that corresponds to the type of the methods argument:
-
stringobject:Let data be a byte buffer that represents the result of encoding the method's argument as UTF-8.
-
Blobobject:Let data be the raw data represented by the
Blobobject.NoteAlthough the actual retrieval of data from aBlobobject can happen asynchronously, the user agent will make sure to queue the data on the channel's underlying data transport in the same order as the send method is called. The byte size of data needs to be known synchronously. -
ArrayBufferobject:Let data be the data stored in the buffer described by the
ArrayBufferobject. -
ArrayBufferViewobject:Let data be the data stored in the section of the buffer described by the
ArrayBufferobject that theArrayBufferViewobject references.
NoteAny data argument type this method has not been overloaded with will result in aTypeError. This includesnullandundefined. -
-
If the byte size of data exceeds the value of
on channel's associatedmaxMessageSize, throw aRTCSctpTransportTypeError. -
Queue data for transmission on channel's underlying data transport. If queuing data is not possible because not enough buffer space is available, throw an
OperationError.NoteThe actual transmission of data occurs in parallel. If sending data leads to an SCTP-level error, the application will be notified asynchronously through.onerror -
Increase the value of the [[BufferedAmount]] slot by the byte size of data.
WebIDLdictionaryRTCDataChannelInit{ booleanordered= true; [EnforceRange] unsigned shortmaxPacketLifeTime; [EnforceRange] unsigned shortmaxRetransmits; USVStringprotocol= ""; booleannegotiated= false; [EnforceRange] unsigned shortid; };
Dictionary RTCDataChannelInit Members
-
orderedof type boolean, 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.
-
maxPacketLifeTimeof type unsigned 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.
-
maxRetransmitsof type unsigned 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.
-
protocolof type USVString, defaulting to"" -
Subprotocol name used for this channel.
-
negotiatedof type boolean, 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 corresponding
object. If set to true, it is up to the application to negotiate the channel and create anRTCDataChannelobject with the sameRTCDataChannelat the other peer.idNoteIf 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. -
idof type unsigned short -
Sets the channel ID when
is true. Ignored whennegotiatedis false.negotiated
WebIDLenumRTCDataChannelState{ "connecting", "open", "closing", "closed" };
RTCDataChannelState Enumeration description
|
|
|---|---|
connecting
|
The user agent is attempting to establish the underlying
data transport. This is the initial state of an
|
open
|
The underlying data transport is established and communication is possible. |
closing
|
The procedure to close down the underlying data transport has started. |
closed
|
The underlying data transport has been |
6.3
RTCDataChannelEvent
The datachannel event uses the interface.
RTCDataChannelEvent
WebIDL[Exposed=Window] interfaceRTCDataChannelEvent: Event {constructor(DOMString type,RTCDataChannelEventIniteventInitDict); readonly attributeRTCDataChannelchannel; };
Constructors
-
RTCDataChannelEvent.constructor()
Attributes
-
channelof type, readonlyRTCDataChannel -
The
attribute represents thechannelobject associated with the event.RTCDataChannel
WebIDLdictionaryRTCDataChannelEventInit: EventInit { requiredRTCDataChannelchannel; };
Dictionary RTCDataChannelEventInit Members
-
channelof type, requiredRTCDataChannel -
The
object to be announced by the event.RTCDataChannel
6.4 Garbage Collection
An object MUST not be garbage collected if its
RTCDataChannel
-
[[ReadyState]] slot is "
" and at least one event listener is registered forconnectingopenevents,messageevents,errorevents,closingevents, orcloseevents. -
[[ReadyState]] slot is "
" and at least one event listener is registered foropenmessageevents,errorevents,closingevents, orcloseevents. -
[[ReadyState]] slot is "
" and at least one event listener is registered forclosingerrorevents, orcloseevents. -
underlying data transport is established and data is queued to be transmitted.
7. Peer-to-peer DTMF
This section describes an interface on to send DTMF
(phone keypad) values across an RTCRtpSender. Details of how
DTMF is sent to the other peer are described in [RFC7874].
RTCPeerConnection
7.1 RTCRtpSender Interface Extensions
The Peer-to-peer DTMF API extends the interface as
described below.
RTCRtpSender
WebIDL partial interfaceRTCRtpSender{ readonly attributeRTCDTMFSender?dtmf; };
Attributes
-
dtmfof type, readonly, nullableRTCDTMFSender -
On getting, the
attribute returns the value of the [[Dtmf]] internal slot, which represents adtmfwhich can be used to send DTMF, orRTCDTMFSendernullif unset. The [[Dtmf]] internal slot is set when the kind of an's [[SenderTrack]] isRTCRtpSender"audio".
7.2
RTCDTMFSender
To create an RTCDTMFSender, the user agent MUST run the following steps:
-
Let dtmf be a newly created
object.RTCDTMFSender -
Let dtmf have a [[Duration]] internal slot.
-
Let dtmf have a [[InterToneGap]] internal slot.
-
Let dtmf have a [[ToneBuffer]] internal slot.
WebIDL[Exposed=Window] interfaceRTCDTMFSender: EventTarget { undefinedinsertDTMF(DOMString tones, optional unsigned long duration = 100, optional unsigned long interToneGap = 70); attribute EventHandlerontonechange; readonly attribute booleancanInsertDTMF; readonly attribute DOMStringtoneBuffer; };
Attributes
-
ontonechangeof type EventHandler -
The event type of this event handler is
.tonechange -
canInsertDTMFof type boolean, readonly -
Whether the
dtmfSender is capable of sending DTMF. On getting, the user agent MUST return the result of running determine if DTMF can be sent for dtmfSender.RTCDTMFSender -
toneBufferof type DOMString, readonly -
The
attribute MUST return a list of the tones remaining to be played out. For the syntax, content, and interpretation of this list, seetoneBuffer.insertDTMF
Methods
-
insertDTMF -
An
object'sRTCDTMFSendermethod is used to send DTMF tones.insertDTMFThe 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 d MUST 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 considered unrecognized.
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.
The interToneGap 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 browser MAY increase the duration and interToneGap times to cause the times that DTMF start and stop to align with the boundaries of RTP packets but it MUST not increase either of them by more than the duration of a single RTP audio packet.
When the
insertDTMF()method is invoked, the user agent MUST run the following steps:- Let sender be the
used to send DTMF.RTCRtpSender -
Let transceiver be the
object associated with sender.RTCRtpTransceiver - Let dtmf be the
associated with sender.RTCDTMFSender - If determine if DTMF can be sent for
dtmf returns
false, throw anInvalidStateError. - Let tones be the method's first argument.
- Let duration be the method's second argument.
- Let interToneGap be the method's third argument.
- If
tones contains any
unrecognizedcharacters, throw anInvalidCharacterError. - Set the object's [[ToneBuffer]] slot to tones.
- Set dtmf.[[Duration]] to the value of duration.
- Set dtmf.[[InterToneGap]] to the value of interToneGap.
- If the value of duration is less than 40 ms, set dtmf.[[Duration]] to 40 ms.
- If the value of duration parameter is greater than 6000 ms, set dtmf.[[Duration]] to 6000 ms.
- If the value of interToneGap is less than 30 ms, set dtmf.[[InterToneGap]] to 30 ms.
- If the value of interToneGap is greater than 6000 ms, set dtmf.[[InterToneGap]] to 6000 ms.
- If [[ToneBuffer]] slot is an empty string, abort these steps.
- If a
Playout task is scheduled to be run, abort these
steps; otherwise queue a task that runs the following steps
(Playout task):
- If
transceiver.[[CurrentDirection]] is
neither "
" nor "sendrecv", abort these steps.sendonly - If the [[ToneBuffer]] slot contains the empty
string, fire an event named
using thetonechangeinterface with theRTCDTMFToneChangeEventattribute set to an empty string at thetoneobject and abort these steps.RTCDTMFSender - Remove the first character from the [[ToneBuffer]] slot and let that character be tone.
- If tone is
","delay sending tones for2000ms on the associated RTP media stream, and queue a task to be executed in2000ms from now that runs the steps labelled Playout task. - If tone is not
","start playout of tone 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 the steps labelled Playout task. - Fire an event named
using thetonechangeinterface with theRTCDTMFToneChangeEventattribute set to tone at thetoneobject.RTCDTMFSender
- If
transceiver.[[CurrentDirection]] is
neither "
Since
replaces the tone buffer, in order to add to the DTMF tones being played, it is necessary to callinsertDTMFwith a string containing both the remaining tones (stored in the [[ToneBuffer]] slot) and the new tones appended together. CallinginsertDTMFwith an empty tones parameter can be used to cancel all tones queued to play after the currently playing tone.insertDTMF - Let sender be the
7.3 canInsertDTMF algorithm
To determine if DTMF can be sent for an
instance dtmfSender, the user agent MUST queue a task that
runs the following steps:
RTCDTMFSender
- Let sender be the
associated with dtmfSender.RTCRtpSender - Let transceiver be the
associated with sender.RTCRtpTransceiver - Let connection be the
associated with transceiver.RTCPeerConnection - If connection's
is not "RTCPeerConnectionState" returnconnectedfalse. - If sender.[[SenderTrack]] is
nullreturnfalse. - If transceiver.[[CurrentDirection]] is neither
"
" nor "sendrecv" returnsendonlyfalse. - If
sender.[[SendEncodings]]
[0].isactivefalsereturnfalse. - If no codec with mimetype
"audio/telephone-event"has been negotiated for sending with this sender, returnfalse. - Otherwise, return
true.
7.4
RTCDTMFToneChangeEvent
The event uses the tonechange
interface.
RTCDTMFToneChangeEvent
WebIDL[Exposed=Window] interfaceRTCDTMFToneChangeEvent: Event {constructor(DOMString type, optionalRTCDTMFToneChangeEventIniteventInitDict = {}); readonly attribute DOMStringtone; };
Constructors
-
RTCDTMFToneChangeEvent.constructor()
Attributes
-
toneof type DOMString, readonly -
The
attribute contains the character for the tone (includingtone",") that has just begun playout (see). 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.insertDTMF
WebIDL dictionaryRTCDTMFToneChangeEventInit: EventInit { DOMStringtone= ""; };
Dictionary RTCDTMFToneChangeEventInit Members
-
toneof type DOMString, defaulting to"" -
The
attribute contains the character for the tone (includingtone",") that has just begun playout (see). 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.insertDTMF
8. Statistics Model
8.1 Introduction
The basic statistics model is that the browser maintains a set of statistics for monitored objects, in the form of stats objects.
A group of related objects may be referenced by a selector. The selector may, for example, be a
MediaStreamTrack. For a track to be a valid selector, it MUST be
a MediaStreamTrack that is sent or received by the
object on which the stats request was issued.
The calling Web application provides the selector to the
RTCPeerConnectiongetStats() method and the browser emits (in the
JavaScript) a set of statistics that are relevant to the selector,
according to the stats selection algorithm. Note that that
algorithm takes the sender or receiver of a selector.
The statistics returned in stats objects are designed in such a
way that repeated queries can be linked by the RTCStats 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.
id
With a few exceptions, monitored objects, once created, exist
for the duration of their associated . This
ensures statistics from them are available in the result from
RTCPeerConnectiongetStats() even past the associated peer
connection being d.
close
Only a few monitored objects have shorter 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 the interface as
described below.
RTCPeerConnection
WebIDL partial interfaceRTCPeerConnection{ Promise<RTCStatsReport>getStats(optional MediaStreamTrack? selector = null); };
Methods
-
getStats -
Gathers stats for the given selector and reports the result asynchronously.
When the
getStats()method is invoked, the user agent MUST run the following steps:-
Let selectorArg be the method's first argument.
-
Let connection be the
object on which the method was invoked.RTCPeerConnection -
If selectorArg is
null, let selector benull. -
If selectorArg is a
MediaStreamTracklet selector be anorRTCRtpSenderon connection whichRTCRtpReceiverattribute matches selectorArg. If no such sender or receiver exists, or if more than one sender or receiver fit this criteria, return a promise rejected with a newly createdtrackInvalidAccessError. -
Let p be a new promise.
-
Run the following steps in parallel:
-
Gather the stats indicated by selector according to the stats selection algorithm.
-
Resolve p with the resulting
object, containing the gathered stats.RTCStatsReport
-
-
Return p.
-
8.3
RTCStatsReport Object
The getStats() method delivers a successful
result in the form of an object. An
RTCStatsReport object is a map between strings that identify the
inspected objects (RTCStatsReport attribute in id
instances), and their corresponding RTCStats-derived
dictionaries.
RTCStats
An may be composed of several RTCStatsReport-derived
dictionaries, each reporting stats for one underlying object that the
implementation thinks is relevant for the selector. One
achieves the total for the selector by summing over all the
stats of a certain type; for instance, if an RTCStats uses
multiple SSRCs to carry its track over the network, the
RTCRtpSender may contain one RTCStatsReport-derived dictionary
per SSRC (which can be distinguished by the value of the
RTCStatsssrc stats attribute).
WebIDL[Exposed=Window]
interface RTCStatsReport {
readonly maplike<DOMString, object>;
};
Use these to retrieve the various dictionaries descended from
that this stats report is composed of. The set of
supported property names [WEBIDL] is defined as the ids of all
the RTCStats-derived dictionaries that have been generated for
this stats report.
RTCStats
8.4
RTCStats Dictionary
An dictionary represents the stats object
constructed by inspecting a specific monitored object. The
RTCStats dictionary is a base type that specifies as set of
default attributes, such as RTCStats and
timestamp. Specific stats are added by extending the
type dictionary.
RTCStats
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, applications MUST 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, if
bytesSent and
packetsSent 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 implementations MUST return
synchronized values for all stats in an -derived
dictionary.
RTCStats
WebIDLdictionaryRTCStats{ required DOMHighResTimeStamptimestamp; required RTCStatsTypetype; required DOMStringid; };
Dictionary RTCStats Members
RTCStats-
timestampof type DOMHighResTimeStamp -
The
, of typetimestampDOMHighResTimeStamp, associated with this object. The time is relative to the UNIX epoch (Jan 1, 1970, UTC). For statistics that came from a remote source (e.g., from received RTCP packets),represents the time at which the information arrived at the local endpoint. The remote timestamp can be found in an additional field in antimestamp-derived dictionary, if applicable.RTCStats -
typeof typeRTCStatsType -
The type of this object.
The
attribute MUST be initialized to the name of the most specific type thistypedictionary represents.RTCStats -
idof type DOMString -
A unique
that is associated with the object that was inspected to produce thisidobject. TwoRTCStatsobjects, extracted from two differentRTCStatsobjects, MUST have the same id if they were produced by inspecting the same underlying object.RTCStatsReportStats ids MUST 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.
NoteA 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 for RTCStatsType, and the dictionaries
derived from RTCStats that they indicate, are documented in
[WEBRTC-STATS].
8.5 The stats selection algorithm
The stats selection algorithm is as follows:
- Let result be an empty
.RTCStatsReport - If
selector is
null, gather stats for the whole connection, add them to result, return result, and abort these steps. -
If selector is an
, gather stats for and add the following objects to result:RTCRtpSender- All
RTCOutboundRtpStreamStatsobjects representing RTP streams being sent by selector. - All stats objects referenced directly or indirectly by the
RTCOutboundRtpStreamStatsobjects added.
- All
-
If selector is an
, gather stats for and add the following objects to result:RTCRtpReceiver- All
RTCInboundRtpStreamStatsobjects representing RTP streams being received by selector. - All stats objects referenced directly or indirectly by the
RTCInboundRtpStreamStatsadded.
- All
- Return result.
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 implementation MUST support generating statistics of the following
s when the corresponding objects exist on a
type, with the fields that are listed when they are
valid for that object in addition to the generic fields defined in
the RTCPeerConnection dictionary:
RTCStats
An implementation MAY support generating any other statistic defined in [WEBRTC-STATS], and MAY 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:
async function gatherStats(pc) {
try {
const [sender] = pc.getSenders();
const baselineReport = await sender.getStats();
await new Promise(resolve => setTimeout(resolve, aBit)); // wait a bit
const currentReport = await sender.getStats();
// compare the elements from the current report with the baseline
for (const now of currentReport.values()) {
if (now.type != 'outbound-rtp') continue;
// get the corresponding stats from the baseline report
const 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
The MediaStreamTrack interface, as defined in the
[GETUSERMEDIA] specification, typically represents a stream of
data of audio or video. One or more MediaStreamTracks can be
collected in a MediaStream (strictly speaking, a MediaStream
as defined in [GETUSERMEDIA] may contain zero or more
MediaStreamTrack objects).
A MediaStreamTrack 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 the MediaStreamTrack object will be described in
this section. How the media is transmitted to the peer is described
in [RFC8834], [RFC7874], and [RFC8835].
A MediaStreamTrack sent to another peer will appear as one and
only one MediaStreamTrack to the recipient. A peer is defined as
a user agent that supports this specification. In addition, the
sending side application can indicate what MediaStream object(s)
the MediaStreamTrack is a member of. The corresponding
MediaStream object(s) on the receiver side will be created (if
not already present) and populated accordingly.
As also described earlier in this document, the objects
and RTCRtpSender can be used by the
application to get more fine grained control over the transmission
and reception of RTCRtpReceiverMediaStreamTracks.
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 jointly MUST be in the same
MediaStreamTrack and the codecs SHOULD be able to encode, or
discard, all the channels in the track.
The concepts of an input and output to a given MediaStreamTrack
apply in the case of MediaStreamTrack objects transmitted over
the network as well. A MediaStreamTrack created by an
object (as described previously in this
document) will take as input the data received from a remote peer.
Similarly, a RTCPeerConnectionMediaStreamTrack 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 an
object.
RTCPeerConnection
The concept of duplicating MediaStream and MediaStreamTrack
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 different MediaStreamTrack objects into new
MediaStream objects is useful in certain situations.
In this document, we only specify aspects of the following objects
that are relevant when used along with an .
Please refer to the original definitions of the objects in the
[GETUSERMEDIA] document for general information on using
RTCPeerConnectionMediaStream and MediaStreamTrack.
9.2 MediaStream
9.2.1 id
The id attribute specified in MediaStream
returns an id that is unique to this stream, so that streams can be
recognized at the remote end of the API.
RTCPeerConnection
When a MediaStream is created to represent a stream obtained
from a remote peer, the id attribute is initialized
from information provided by the remote source.
The id of a MediaStream 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
using 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).
RTCPeerConnection
9.3 MediaStreamTrack
A MediaStreamTrack object's reference to its MediaStream in
the non-local media source case (an RTP source, as is the case for
each MediaStreamTrack associated with an ) is
always strong.
RTCRtpReceiver
Whenever an receives data on an RTP source whose
corresponding RTCRtpReceiverMediaStreamTrack is muted, but not ended, and the
[[Receptive]] slot of the object the
RTCRtpTransceiver is a member of is RTCRtpReceivertrue, it MUST queue
a task to set the muted state of the corresponding
MediaStreamTrack to false.
When one of the SSRCs for RTP source media streams received by an
is removed either due to reception of a BYE or via
timeout, it MUST queue a task to set the muted state of the
corresponding RTCRtpReceiverMediaStreamTrack to true. Note that
can also lead to the setting of the muted state of the
setRemoteDescription to the value tracktrue.
The procedures add a track, remove a track and set a track's muted state are specified in [GETUSERMEDIA].
When a MediaStreamTrack track produced by an
receiver has RTCRtpReceiverended
[GETUSERMEDIA] (such as via a call to
receiver..trackstop), the user agent MAY choose to free resources
allocated for the incoming stream, by for instance turning off the
decoder of receiver.
9.3.1 MediaTrackSupportedConstraints, MediaTrackCapabilities, MediaTrackConstraints and MediaTrackSettings
The concept of constraints and constrainable properties, including
MediaTrackConstraints (MediaStreamTrack.getConstraints(), MediaStreamTrack.applyConstraints()), and MediaTrackSettings
(MediaStreamTrack.getSettings()) are
outlined in [GETUSERMEDIA]. However, the constrainable
properties of tracks sourced from a peer connection are different
than those sourced by getUserMedia(); the
constraints and settings applicable to MediaStreamTracks
sourced from a remote source are defined here. The settings
of a remote track represent the latest frame received.
MediaStreamTrack.getCapabilities()
MUST always return the empty set and
MediaStreamTrack.applyConstraints()
MUST always reject with OverconstrainedError on remote tracks for constraints
defined here.
The following constrainable properties are defined to apply to
video MediaStreamTracks sourced from a remote source:
| Property Name | Values | Notes |
|---|---|---|
| width |
ConstrainULong
|
As a setting, this is the width, in pixels, of the latest frame received. |
| height |
ConstrainULong
|
As a setting, this is the height, in pixels, of the latest frame received. |
| frameRate |
ConstrainDouble
|
As a setting, this is an estimate of the frame rate based on recently received frames. |
| aspectRatio |
ConstrainDouble
|
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 audio MediaStreamTracks sourced from a remote 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.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const constraints = {audio: true, video: true};
const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]};
const pc = new RTCPeerConnection(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);
}
};
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 initiate
function start() {
addCameraMic();
}
// add camera and microphone to connection
async function addCameraMic() {
try {
// get a local stream, show it in a self-view and add it to be sent
const stream = await navigator.mediaDevices.getUserMedia(constraints);
for (const track of 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 answer
if (description.type == 'offer') {
if (!selfView.srcObject) {
// blocks negotiation on permission (not recommended in production code)
await addCameraMic();
}
await pc.setLocalDescription();
signaling.send({description: pc.localDescription});
}
} else if (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.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const 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.
async function warmup(isAnswerer) {
pc = new RTCPeerConnection(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 = new MediaStream();
}
remoteView.srcObject.addTrack(track);
}
if (isAnswerer) {
if (track.kind == 'audio') {
audio = transceiver;
} else if (track.kind == 'video') {
video = transceiver;
}
if (started) await addCameraMicWarmedUp();
}
} 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) await addCameraMicWarmedUp();
} catch (err) {
console.error(err);
}
}
// call start() after warmup() to begin transmitting media from both ends
function start() {
signaling.send({start: true});
signaling.onmessage({data: {start: true}});
}
// add camera and microphone to already warmed-up connection
async function addCameraMicWarmedUp() {
const stream = selfView.srcObject;
if (audio && video && stream) {
await Promise.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;
await addCameraMicWarmedUp();
} else if (description) {
await pc.setRemoteDescription(description);
// if we got an offer, we need to reply with an answer
if (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.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const constraints = {audio: true, video: true};
const configuration = {'iceServers': [{'urls': 'stun:stun.example.org'}]};
let pc;
// call start() to initiate
async function start() {
pc = new RTCPeerConnection(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 sent
const 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 answer
if (description.type == 'offer') {
await pc.setLocalDescription();
signaling.send({description: pc.localDescription});
}
} else if (candidate) {
await pc.addIceCandidate(candidate);
}
} catch (err) {
console.error(err);
}
};
10.4 Peer-to-peer Data Example
This example shows how to create an object and
perform the offer/answer exchange required to connect the channel
to the other peer. The RTCDataChannel is used in the context of
a simple chat application using an RTCDataChannelinput field for
user input.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]};
let pc, channel;
// call start() to initiate
function start() {
pc = new RTCPeerConnection(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.onkeypress = ({keyCode}) => {
// only send when user presses enter
if (keyCode != 13) return;
channel.send(input.value);
}
}
signaling.onmessage = async ({data: {description, candidate}}) => {
if (!pc) start(false);
try {
if (description) {
await pc.setRemoteDescription(description);
// if we got an offer, we need to reply with an answer
if (description.type == 'offer') {
await pc.setLocalDescription();
signaling.send({description: pc.localDescription});
}
} else if (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.
10.6 DTMF Example
Examples assume that sender is an .
RTCRtpSender
Sending the DTMF signal "1234" with 500 ms duration per tone:
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".
async function sendDTMF() {
if (sender.dtmf.canInsertDTMF) {
sender.dtmf.insertDTMF('123');
await new Promise(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 using
lightKey(key) while the tone is playing
(assuming that lightKey("") will darken
all the keys):
const wait = ms => new Promise(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 starts
await wait(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.
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 begun
if (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:
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 "" state). The rest
of the application may use any and all modification methods and
attributes, without worrying about signaling state races.
stable
It designates different roles to the two peers, with behavior to resolve signaling collisions between them:
-
The polite peer uses rollback to avoid collision with an incoming offer.
-
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 a
polite boolean variable indicating the designated role:
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const constraints = {audio: true, video: true};
const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]};
const pc = new RTCPeerConnection(configuration);
// call start() anytime on either end to add camera and microphone to connection
async function start() {
try {
const stream = await navigator.mediaDevices.getUserMedia(constraints);
for (const track of 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 errors
let makingOffer = false;
let ignoreOffer = false;
let isSettingRemoteAnswerPending = false;
// 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 {
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});
}
} else if (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 of
(without arguments) and
setLocalDescription (with implicit rollback)
to avoid races with other signaling messages being serviced.
setRemoteDescription
The ignoreOffer variable is needed, because the
object on the impolite side is never told about
ignored offers. We must therefore suppress errors from incoming
candidates belonging to such offers.
RTCPeerConnection
11. Error Handling
Some operations throw or fire . This is an extension of
RTCErrorDOMException that carries additional WebRTC-specific information.
11.1
RTCError Interface
WebIDL[Exposed=Window] interfaceRTCError: DOMException {constructor(RTCErrorInitinit, optional DOMString message = ""); readonly attributeRTCErrorDetailTypeerrorDetail; readonly attribute long?sdpLineNumber; readonly attribute long?sctpCauseCode; readonly attribute unsigned long?receivedAlert; readonly attribute unsigned long?sentAlert; };
11.1.1 Constructors
-
constructor() -
Run the following steps:
-
Let init be the constructor's first argument.
-
Let message be the constructor's second argument.
-
Let e be a new
object.RTCError -
Invoke the
DOMExceptionconstructor of e with theargument set to message and themessagenameargument set to"OperationError".NoteThis name does not have a mapping to a legacy code so e.
codewill return 0. -
Set all
attributes of e to the value of the corresponding attribute in init if it is present, otherwise set it toRTCErrornull. -
Return e.
-
11.1.2 Attributes
-
errorDetailof type RTCErrorDetailType, readonly -
The WebRTC-specific error code for the type of error that occurred.
-
sdpLineNumberof type long, readonly, nullable -
If
is "errorDetail" this is the line number where the error was detected (the first line has line number 1).sdp-syntax-error -
sctpCauseCodeof type long, readonly, nullable -
If
is "errorDetail" this is the SCTP cause code of the failed SCTP negotiation.sctp-failure -
receivedAlertof type unsigned long, readonly, nullable -
If
is "errorDetail" and a fatal DTLS alert was received, this is the value of the DTLS alert received.dtls-failure -
sentAlertof type unsigned long, readonly, nullable -
If
is "errorDetail" and a fatal DTLS alert was sent, this is the value of the DTLS alert sent.dtls-failure -
(Feature at Risk) Issue 1
All attributes defined in
are marked at risk due to lack of implementation (RTCError,errorDetail,sdpLineNumber,sctpCauseCodeandreceivedAlert). This does not include attributes inherited fromsentAlertDOMException.
RTCErrorInit Dictionary
WebIDLdictionaryRTCErrorInit{ requiredRTCErrorDetailTypeerrorDetail; longsdpLineNumber; longsctpCauseCode; unsigned longreceivedAlert; unsigned longsentAlert; };
The errorDetail, sdpLineNumber, sctpCauseCode,
receivedAlert and sentAlert members of have the same
definitions as the attributes of the same name of RTCErrorInit.
RTCError
11.2
RTCErrorDetailType Enum
WebIDLenumRTCErrorDetailType{ "data-channel-failure", "dtls-failure", "fingerprint-failure", "sctp-failure", "sdp-syntax-error", "hardware-encoder-not-available", "hardware-encoder-error" };
| Enumeration description | |
|---|---|
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. The
contains information relating to the nature of error. If a
fatal DTLS alert was received, the
attribute is set to the value of the DTLS alert received. If a
fatal DTLS alert was sent, the attribute
is set to the value of the DTLS alert sent.
|
fingerprint-failure
|
The '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
"".
|
sctp-failure
|
The SCTP negotiation has failed or the connection has been
terminated with a fatal error. The
attribute is set to the SCTP cause code.
|
sdp-syntax-error
|
The SDP syntax is not valid. The
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.3
RTCErrorEvent Interface
The interface is defined for cases when an
RTCErrorEvent is raised as an event:
RTCError
WebIDL[Exposed=Window] interfaceRTCErrorEvent: Event {constructor(DOMString type,RTCErrorEventIniteventInitDict); [SameObject] readonly attributeRTCErrorerror; };
11.3.1 Constructors
-
constructor() -
Constructs a new
.RTCErrorEvent
11.3.2 Attributes
11.4
RTCErrorEventInit Dictionary
WebIDL dictionaryRTCErrorEventInit: EventInit { requiredRTCErrorerror; };
11.4.1 Dictionary RTCErrorEventInit Members
12. Event summary
This section is non-normative.
The following events fire on objects:
RTCDataChannel
| Event name | Interface | Fired when... |
|---|---|---|
open
|
Event
|
The object's underlying data transport
has been established (or re-established).
|
message
|
MessageEvent
[html]
|
A message was successfully received. |
bufferedamountlow
|
Event
|
The object's
decreases from above its
to less than or
equal to its .
|
error
|
|
An error occurred on the data channel. |
closing
|
Event
|
The object transitions to the
"" state
|
close
|
Event
|
The object's underlying data transport
has been closed.
|
The following events fire on objects:
RTCPeerConnection
| Event name | Interface | Fired when... |
|---|---|---|
track
|
|
New incoming media has been negotiated for a specific
, and that receiver's
has been added to any associated remote MediaStreams.
|
negotiationneeded
|
Event
|
The browser wishes to inform the application that session negotiation needs to be done (i.e. a createOffer call followed by setLocalDescription). |
signalingstatechange
|
Event
|
The signaling state has changed. This state change is the
result of either or
being invoked.
|
iceconnectionstatechange
|
Event
|
The 's ICE connection state has
changed.
|
icegatheringstatechange
|
Event
|
The 's ICE gathering state has
changed.
|
icecandidate
|
|
A new is made available to the script.
|
connectionstatechange
|
Event
|
The .
has changed.
|
icecandidateerror
|
|
A failure occured when gathering ICE candidates. |
| datachannel |
|
A new is dispatched to the script in response
to the other peer creating a channel.
|
The following events fire on objects:
RTCDTMFSender
| Event name | Interface | Fired when... |
|---|---|---|
tonechange
|
|
The object has either just begun playout of a
tone (returned as the attribute)
or just ended the playout of tones in the
(returned as an empty value in the
attribute).
|
The following events fire on objects:
RTCIceTransport
| Event name | Interface | Fired when... |
|---|---|---|
statechange
|
Event
|
The state changes.
|
gatheringstatechange
|
Event
|
The gathering state changes.
|
selectedcandidatepairchange
|
Event
|
The 's selected candidate pair changes.
|
The following events fire on objects:
RTCDtlsTransport
| Event name | Interface | Fired when... |
|---|---|---|
statechange
|
Event
|
The state changes.
|
error
|
|
An error occurred on the (either
"" or
"").
|
The following events fire on objects:
RTCSctpTransport
| Event name | Interface | Fired when... |
|---|---|---|
statechange
|
Event
|
The 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 the 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.
RTCIceTransportPolicy
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:
- A user agent will always request permission from the correspondent user agent to communicate using ICE. This ensures that the user agent can only send to partners who you have shared credentials with.
- A user agent will always request ongoing permission to continue sending using ICE continued consent. This enables a receiver to withdraw consent to receive.
- A user agent will always encrypt data, with strong per-session keying (DTLS-SRTP).
- A user agent will always use congestion control. This ensures that WebRTC cannot be used to flood the network.
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 using
postMessage(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 the objects, to reduce memory attack surface.
RTCCertificate
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 the
.RTCRtpSender and
getCapabilities.RTCRtpReceiver 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 during session negotiation. That
information is in most cases persistent across time and origins, and
increases the fingerprint surface of a given device.
getCapabilities
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
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 like
setRemoteDescription if the other endpoint does not
negotiate sending. Applications need to be on guard against
malevolent SDP.
ontrack
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 the IETF 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 at W3C groups to effectively and consistently standardise RTT support internationally.
A. 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.
The and RTCRtpSender objects were initially
described in the W3C ORTC
CG, and have been adapted for use in this specification.
RTCRtpReceiver
B. References
B.1 Normative 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 2019. W3C Working Draft. URL: https://www.w3.org/TR/FileAPI/
- [FIPS-180-4]
- FIPS PUB 180-4 Secure Hash Standard. U.S. Department of Commerce/National Institute of Standards and Technology. 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 2021. W3C Candidate Recommendation. URL: https://www.w3.org/TR/mediacapture-streams/
- [hr-time]
- High Resolution Time Level 2. Ilya Grigorik. W3C. 21 November 2019. W3C Recommendation. URL: https://www.w3.org/TR/hr-time-2/
- [HTML]
- HTML Standard. Anne van Kesteren; Domenic Denicola; 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/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/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/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/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/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/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/rfc5246
- [RFC5285]
- A General Mechanism for RTP Header Extensions. D. Singer; H. Desineni. IETF. July 2008. Proposed Standard. URL: https://tools.ietf.org/html/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/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/rfc5506
- [RFC5888]
- The Session Description Protocol (SDP) Grouping Framework. G. Camarillo; H. Schulzrinne. IETF. June 2010. Proposed Standard. URL: https://tools.ietf.org/html/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/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/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/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/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/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/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/rfc7675
- [RFC7874]
- WebRTC Audio Codec and Processing Requirements. JM. Valin; C. Bran. IETF. May 2016. Proposed Standard. URL: https://tools.ietf.org/html/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/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/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/rfc8445
- [RFC8826]
- Security Considerations for WebRTC. E. Rescorla. IETF. January 2021. Proposed Standard. URL: https://tools.ietf.org/html/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/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/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/rfc8834
- [RFC8835]
- Transports for WebRTC. H. Alvestrand. IETF. January 2021. Proposed Standard. URL: https://tools.ietf.org/html/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/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/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/rfc8843
- [RFC8851]
- RTP Payload Format Restrictions. A.B. Roach, Ed.. IETF. January 2021. Proposed Standard. URL: https://tools.ietf.org/html/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/rfc8853
- [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/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/
- [WEBRTC-STATS]
- Identifiers for WebRTC's Statistics API. Harald Alvestrand; Varun Singh; Henrik Boström. W3C. 20 January 2021. W3C Candidate Recommendation. 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
B.2 Informative references
- [API-DESIGN-PRINCIPLES]
- API Design Principles. Domenic Denicola. 29 December 2015. URL: https://w3ctag.github.io/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://tools.ietf.org/html/rfc4103
- [RFC6236]
- Negotiation of Generic Image Attributes in the Session Description Protocol (SDP). I. Johansson; K. Jung. IETF. May 2011. Proposed Standard. URL: https://tools.ietf.org/html/rfc6236
- [RFC8825]
- Overview: Real-Time Protocols for Browser-Based Applications. H. Alvestrand. IETF. January 2021. Proposed Standard. URL: https://tools.ietf.org/html/rfc8825
- [RFC8827]
- WebRTC Security Architecture. E. Rescorla. IETF. January 2021. Proposed Standard. URL: https://tools.ietf.org/html/rfc8827
- [RFC8828]
- WebRTC IP Address Handling Requirements. J. Uberti; G. Shieh. IETF. January 2021. Proposed Standard. URL: https://tools.ietf.org/html/rfc8828
- [xhr]
- XMLHttpRequest Standard. Anne van Kesteren. WHATWG. Living Standard. URL: https://xhr.spec.whatwg.org/